org.springframework.transaction.reactive.TransactionalOperator Java Examples

The following examples show how to use org.springframework.transaction.reactive.TransactionalOperator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReactiveIdGeneratorsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void idGenerationByBeansShouldWorkWork(@Autowired ThingWithIdGeneratedByBeanRepository repository) {

	List<ThingWithIdGeneratedByBean> savedThings = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> repository.save(new ThingWithIdGeneratedByBean("WrapperService")))
		.as(StepVerifier::create)
		.recordWith(() -> savedThings)
		.consumeNextWith(savedThing -> {

			assertThat(savedThing.getName()).isEqualTo("WrapperService");
			assertThat(savedThing.getTheId()).isEqualTo("ReactiveID.");
		})
		.verifyComplete();

	verifyDatabase(savedThings.get(0).getTheId(), savedThings.get(0).getName());
}
 
Example #2
Source File: ReactiveNeo4jTransactionManagerTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUseTxFromNeo4jTxManager() {

	ReactiveNeo4jTransactionManager txManager = new ReactiveNeo4jTransactionManager(driver, ReactiveDatabaseSelectionProvider
		.createStaticDatabaseSelectionProvider(databaseName));
	TransactionalOperator transactionalOperator = TransactionalOperator.create(txManager);

	transactionalOperator
		.execute(transactionStatus -> TransactionSynchronizationManager
			.forCurrentTransaction().doOnNext(tsm -> {
				assertThat(tsm.hasResource(driver)).isTrue();
				transactionStatus.setRollbackOnly();
			}).then(retrieveReactiveTransaction(driver, databaseName))
		)
		.as(StepVerifier::create)
		.expectNextCount(1L)
		.verifyComplete();

	verify(driver).rxSession(any(SessionConfig.class));

	verify(session).beginTransaction(any(TransactionConfig.class));
	verify(session).close();
	verify(transaction).rollback();
	verify(transaction, never()).commit();
}
 
Example #3
Source File: ReactiveNeo4jTransactionManagerTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void shouldSynchronizeWithExternalWithCommit() {

	R2dbcTransactionManager t = new R2dbcTransactionManager(new H2ConnectionFactory(
		H2ConnectionConfiguration.builder().inMemory("test").build()));

	TransactionalOperator transactionalOperator = TransactionalOperator.create(t);

	transactionalOperator
		.execute(transactionStatus -> TransactionSynchronizationManager
			.forCurrentTransaction().doOnNext(tsm -> assertThat(tsm.hasResource(driver)).isFalse())
			.then(retrieveReactiveTransaction(driver, databaseName))
			.flatMap(ignoredNativeTx -> TransactionSynchronizationManager.forCurrentTransaction()
				.doOnNext(tsm -> assertThat(tsm.hasResource(driver)).isTrue()))
		)
		.as(StepVerifier::create)
		.expectNextCount(1L)
		.verifyComplete();

	verify(driver).rxSession(any(SessionConfig.class));

	verify(session).beginTransaction(any(TransactionConfig.class));
	verify(session).close();
	verify(transaction).commit();
	verify(transaction, never()).rollback();
}
 
Example #4
Source File: ReactiveTransactionManagerMixedDatabasesTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void usingAnotherDatabaseDeclarativeFromRepo(@Autowired ReactivePersonRepository repository) {

	ReactiveNeo4jTransactionManager otherTransactionManger = new ReactiveNeo4jTransactionManager(driver,
		ReactiveDatabaseSelectionProvider.createStaticDatabaseSelectionProvider(DATABASE_NAME));
	TransactionalOperator otherTransactionTemplate = TransactionalOperator.create(otherTransactionManger);

	Mono<PersonWithAllConstructor> p =
		repository.save(new PersonWithAllConstructor(null, "Mercury", "Freddie", "Queen", true, 1509L,
			LocalDate.of(1946, 9, 15), null, Collections.emptyList(), null, null))
			.as(otherTransactionTemplate::transactional);

	StepVerifier
		.create(p)
		.expectErrorMatches(e ->
			e instanceof IllegalStateException && e.getMessage().equals(
				"There is already an ongoing Spring transaction for 'boom', but you request the default database"))
		.verify();
}
 
Example #5
Source File: ReactiveTransactionManagerMixedDatabasesTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void usingAnotherDatabaseExplicitTx(@Autowired ReactiveNeo4jClient neo4jClient) {

	TransactionalOperator transactionTemplate = TransactionalOperator.create(neo4jTransactionManager);

	Mono<Long> numberOfNodes = neo4jClient.query("MATCH (n) RETURN COUNT(n)").in(DATABASE_NAME).fetchAs(Long.class)
		.one()
		.as(transactionTemplate::transactional);

	StepVerifier
		.create(numberOfNodes)
		.expectErrorMatches(e ->
			e instanceof IllegalStateException && e.getMessage().equals(
				"There is already an ongoing Spring transaction for the default database, but you request 'boom'"))
		.verify();
}
 
Example #6
Source File: ReactiveCallbacksIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void onBeforeBindShouldBeCalledForAllEntitiesUsingPublisher(@Autowired ReactiveThingRepository repository) {

	ThingWithAssignedId thing1 = new ThingWithAssignedId("id1");
	thing1.setName("A name");
	ThingWithAssignedId thing2 = new ThingWithAssignedId("id2");
	thing2.setName("Another name");
	repository.saveAll(Arrays.asList(thing1, thing2));

	Flux<ThingWithAssignedId> operationUnderTest = repository.saveAll(Flux.just(thing1, thing2));

	List<ThingWithAssignedId> savedThings = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.recordWith(() -> savedThings)
		.expectNextMatches(t -> t.getName().equals("A name (Edited)"))
		.expectNextMatches(t -> t.getName().equals("Another name (Edited)"))
		.verifyComplete();

	verifyDatabase(savedThings);
}
 
Example #7
Source File: ReactiveCallbacksIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void onBeforeBindShouldBeCalledForAllEntitiesUsingIterable(@Autowired ReactiveThingRepository repository) {

	ThingWithAssignedId thing1 = new ThingWithAssignedId("id1");
	thing1.setName("A name");
	ThingWithAssignedId thing2 = new ThingWithAssignedId("id2");
	thing2.setName("Another name");
	repository.saveAll(Arrays.asList(thing1, thing2));

	Flux<ThingWithAssignedId> operationUnderTest = repository.saveAll(Arrays.asList(thing1, thing2));

	List<ThingWithAssignedId> savedThings = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.recordWith(() -> savedThings)
		.expectNextMatches(t -> t.getName().equals("A name (Edited)"))
		.expectNextMatches(t -> t.getName().equals("Another name (Edited)"))
		.verifyComplete();

	verifyDatabase(savedThings);
}
 
Example #8
Source File: ReactiveCallbacksIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void onBeforeBindShouldBeCalledForSingleEntity(@Autowired ReactiveThingRepository repository) {

	ThingWithAssignedId thing = new ThingWithAssignedId("aaBB");
	thing.setName("A name");

	Mono<ThingWithAssignedId> operationUnderTest = Mono.just(thing).flatMap(repository::save);

	List<ThingWithAssignedId> savedThings = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.recordWith(() -> savedThings)
		.expectNextMatches(t -> t.getName().equals("A name (Edited)"))
		.verifyComplete();

	verifyDatabase(savedThings);
}
 
Example #9
Source File: ReactiveFirestoreTransactionManagerTest.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void triggerRollbackCorrectly() {

	FirestoreTemplate template = getFirestoreTemplate();

	ReactiveFirestoreTransactionManager txManager = new ReactiveFirestoreTransactionManager(this.firestoreStub, this.parent);
	TransactionalOperator operator = TransactionalOperator.create(txManager);

	template.findById(Mono.defer(() -> {
		throw new FirestoreDataException("BOOM!");
	}), FirestoreTemplateTests.TestEntity.class)
			.as(operator::transactional)
			.as(StepVerifier::create)
			.expectError()
			.verify();

	verify(this.firestoreStub, times(1)).beginTransaction(any(), any());
	verify(this.firestoreStub, times(0)).commit(any(), any());


	verify(this.firestoreStub, times(1)).rollback(any(), any());
}
 
Example #10
Source File: ReactiveAuditingIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void auditingOfEntityWithGeneratedIdCreationShouldWork(
	@Autowired ImmutableEntityWithGeneratedIdTestRepository repository) {

	List<ImmutableAuditableThingWithGeneratedId> newThings = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> repository.save(new ImmutableAuditableThingWithGeneratedId("A thing")))
		.as(StepVerifier::create)
		.recordWith(() -> newThings)
		.expectNextCount(1L)
		.verifyComplete();

	ImmutableAuditableThingWithGeneratedId savedThing = newThings.get(0);
	assertThat(savedThing.getCreatedAt()).isEqualTo(DEFAULT_CREATION_AND_MODIFICATION_DATE);
	assertThat(savedThing.getCreatedBy()).isEqualTo("A user");

	assertThat(savedThing.getModifiedAt()).isNull();
	assertThat(savedThing.getModifiedBy()).isNull();

	verifyDatabase(savedThing.getId(), savedThing);
}
 
Example #11
Source File: ReactiveIdGeneratorsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void idGenerationWithNewEntityShouldWork(@Autowired ThingWithGeneratedIdRepository repository) {

	List<ThingWithGeneratedId> savedThings = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> repository.save(new ThingWithGeneratedId("WrapperService")))
		.as(StepVerifier::create)
		.recordWith(() -> savedThings)
		.consumeNextWith(savedThing -> {

			assertThat(savedThing.getName()).isEqualTo("WrapperService");
			assertThat(savedThing.getTheId())
				.isNotBlank()
				.matches("thingWithGeneratedId-\\d+");
		})
		.verifyComplete();

	verifyDatabase(savedThings.get(0).getTheId(), savedThings.get(0).getName());
}
 
Example #12
Source File: ReactiveAuditingIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void auditingOfCreationShouldWork(@Autowired ImmutableEntityTestRepository repository) {

	List<ImmutableAuditableThing> newThings = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> repository.save(new ImmutableAuditableThing("A thing")))
		.as(StepVerifier::create)
		.recordWith(() -> newThings)
		.expectNextCount(1L)
		.verifyComplete();

	ImmutableAuditableThing savedThing = newThings.get(0);
	assertThat(savedThing.getCreatedAt()).isEqualTo(DEFAULT_CREATION_AND_MODIFICATION_DATE);
	assertThat(savedThing.getCreatedBy()).isEqualTo("A user");

	assertThat(savedThing.getModifiedAt()).isNull();
	assertThat(savedThing.getModifiedBy()).isNull();

	verifyDatabase(savedThing.getId(), savedThing);
}
 
Example #13
Source File: ReactiveIdGeneratorsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void shouldNotOverwriteExistingId(@Autowired ThingWithGeneratedIdRepository repository) {

	Mono<ThingWithGeneratedId> findAndUpdateAThing = repository.findById(ID_OF_EXISTING_THING)
		.flatMap(thing -> {
			thing.setName("changed");
			return repository.save(thing);
		});

	List<ThingWithGeneratedId> savedThings = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> findAndUpdateAThing)
		.as(StepVerifier::create)
		.recordWith(() -> savedThings)
		.consumeNextWith(savedThing -> {

			assertThat(savedThing.getName()).isEqualTo("changed");
			assertThat(savedThing.getTheId()).isEqualTo(ID_OF_EXISTING_THING);
		})
		.verifyComplete();

	verifyDatabase(savedThings.get(0).getTheId(), savedThings.get(0).getName());
}
 
Example #14
Source File: ReactiveIdGeneratorsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void idGenerationWithNewEntitiesShouldWork(@Autowired ThingWithGeneratedIdRepository repository) {

	List<ThingWithGeneratedId> things = IntStream.rangeClosed(1, 10)
		.mapToObj(i -> new ThingWithGeneratedId("name" + i))
		.collect(toList());

	Set<String> generatedIds = new HashSet<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> repository.saveAll(things))
		.map(ThingWithGeneratedId::getTheId)
		.as(StepVerifier::create)
		.recordWith(() -> generatedIds)
		.expectNextCount(things.size())
		.expectRecordedMatches(recorded -> {
			assertThat(recorded)
				.hasSize(things.size())
				.allMatch(generatedId -> generatedId.matches("thingWithGeneratedId-\\d+"));
			return true;
		})
		.verifyComplete();
}
 
Example #15
Source File: ReactiveFirestoreTransactionManagerTest.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void triggerCommitCorrectly() {

	FirestoreTemplate template = getFirestoreTemplate();

	ReactiveFirestoreTransactionManager txManager = new ReactiveFirestoreTransactionManager(this.firestoreStub, this.parent);
	TransactionalOperator operator = TransactionalOperator.create(txManager);

	template.findById(Mono.just("e1"), FirestoreTemplateTests.TestEntity.class)
			.concatWith(template.findById(Mono.just("e2"), FirestoreTemplateTests.TestEntity.class))
			.as(operator::transactional)
			.as(StepVerifier::create)
			.expectNext(
					new FirestoreTemplateTests.TestEntity("e1", 100L),
					new FirestoreTemplateTests.TestEntity("e2", 100L))
			.verifyComplete();


	verify(this.firestoreStub).beginTransaction(any(), any());
	verify(this.firestoreStub).commit(any(), any());

	GetDocumentRequest request1 = GetDocumentRequest.newBuilder()
			.setName(this.parent + "/testEntities/" + "e1")
			.setTransaction(ByteString.copyFromUtf8("transaction1"))
			.build();
	verify(this.firestoreStub, times(1)).getDocument(eq(request1), any());

	GetDocumentRequest request2 = GetDocumentRequest.newBuilder()
			.setName(this.parent + "/testEntities/" + "e2")
			.setTransaction(ByteString.copyFromUtf8("transaction1"))
			.build();
	verify(this.firestoreStub, times(1)).getDocument(eq(request2), any());
}
 
Example #16
Source File: ReactiveNeo4jTransactionManagerTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSynchronizeWithExternalWithRollback() {

	R2dbcTransactionManager t = new R2dbcTransactionManager(new H2ConnectionFactory(
		H2ConnectionConfiguration.builder().inMemory("test").build()));

	TransactionalOperator transactionalOperator = TransactionalOperator.create(t);

	transactionalOperator
		.execute(transactionStatus -> TransactionSynchronizationManager
			.forCurrentTransaction()
			.doOnNext(tsm -> {
				assertThat(tsm.hasResource(driver)).isFalse();
				transactionStatus.setRollbackOnly();
			})
			.then(retrieveReactiveTransaction(driver, databaseName))
			.flatMap(ignoredNativeTx -> TransactionSynchronizationManager.forCurrentTransaction()
				.doOnNext(tsm -> assertThat(tsm.hasResource(driver)).isTrue()))
		)
		.as(StepVerifier::create)
		.expectNextCount(1L)
		.verifyComplete();

	verify(driver).rxSession(any(SessionConfig.class));

	verify(session).beginTransaction(any(TransactionConfig.class));
	verify(session).close();
	verify(transaction).rollback();
	verify(transaction, never()).commit();
}
 
Example #17
Source File: ReactiveNeo4jTransactionManagerTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void usesBookmarksCorrectly() throws Exception {

	ReactiveNeo4jTransactionManager txManager = new ReactiveNeo4jTransactionManager(driver, ReactiveDatabaseSelectionProvider
		.createStaticDatabaseSelectionProvider(databaseName));

	Neo4jBookmarkManager bookmarkManager = spy(new Neo4jBookmarkManager());
	injectBookmarkManager(txManager, bookmarkManager);

	Bookmark bookmark = new Bookmark() {
		@Override public Set<String> values() {
			return Collections.singleton("blubb");
		}

		@Override public boolean isEmpty() {
			return false;
		}
	};
	when(session.lastBookmark()).thenReturn(bookmark);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(txManager);

	transactionalOperator
		.execute(transactionStatus -> TransactionSynchronizationManager
			.forCurrentTransaction()
			.doOnNext(tsm -> assertThat(tsm.hasResource(driver)).isTrue())
			.then(retrieveReactiveTransaction(driver, databaseName))
		)
		.as(StepVerifier::create)
		.expectNextCount(1L)
		.verifyComplete();

	verify(driver).rxSession(any(SessionConfig.class));
	verify(session).beginTransaction(any(TransactionConfig.class));
	verify(bookmarkManager).getBookmarks();
	verify(session).close();
	verify(transaction).commit();
	verify(bookmarkManager).updateBookmarks(anyCollection(), eq(bookmark));
}
 
Example #18
Source File: ReactiveNeo4jTransactionManagerTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldParticipateInOngoingTransaction() {

	ReactiveNeo4jTransactionManager txManager = new ReactiveNeo4jTransactionManager(driver, ReactiveDatabaseSelectionProvider
		.createStaticDatabaseSelectionProvider(databaseName));
	TransactionalOperator transactionalOperator = TransactionalOperator.create(txManager);

	transactionalOperator
		.execute(outerStatus -> {
			assertThat(outerStatus.isNewTransaction()).isTrue();
			outerStatus.setRollbackOnly();
			return transactionalOperator.execute(innerStatus -> {
				assertThat(innerStatus.isNewTransaction()).isFalse();
				return retrieveReactiveTransaction(driver, databaseName);
			}).then(retrieveReactiveTransaction(driver, databaseName));
		})
		.as(StepVerifier::create)
		.expectNextCount(1L)
		.verifyComplete();

	verify(driver).rxSession(any(SessionConfig.class));

	verify(session).beginTransaction(any(TransactionConfig.class));
	verify(session).close();
	verify(transaction).rollback();
	verify(transaction, never()).commit();
}
 
Example #19
Source File: FirestoreRepositoryIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void transactionalOperatorTest() {
	//tag::repository_transactional_operator[]
	DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
	transactionDefinition.setReadOnly(false);
	TransactionalOperator operator = TransactionalOperator.create(this.txManager, transactionDefinition);
	//end::repository_transactional_operator[]

	//tag::repository_operations_in_a_transaction[]
	User alice = new User("Alice", 29);
	User bob = new User("Bob", 60);

	this.userRepository.save(alice)
			.then(this.userRepository.save(bob))
			.as(operator::transactional)
			.block();

	this.userRepository.findAll()
			.flatMap(a -> {
				a.setAge(a.getAge() - 1);
				return this.userRepository.save(a);
			})
			.as(operator::transactional).collectList().block();

	assertThat(this.userRepository.findAll().map(User::getAge).collectList().block())
			.containsExactlyInAnyOrder(28, 59);
	//end::repository_operations_in_a_transaction[]
}
 
Example #20
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveAllIterableWithAssignedId(@Autowired ReactiveThingRepository repository) {

	ThingWithAssignedId existingThing = new ThingWithAssignedId("anId");
	existingThing.setName("Updated name.");
	ThingWithAssignedId newThing = new ThingWithAssignedId("aaBB");
	newThing.setName("That's the thing.");

	List<ThingWithAssignedId> things = Arrays.asList(existingThing, newThing);

	Flux<ThingWithAssignedId> operationUnderTest = repository.saveAll(things);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.expectNextCount(2L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> {
				Value parameters = parameters("ids", Arrays.asList("anId", "aaBB"));
				return s.run("MATCH (n:Thing) WHERE n.theId IN ($ids) RETURN n.name as name ORDER BY n.name ASC",
					parameters)
					.records();
			},
			RxSession::close
		)
		.map(r -> r.get("name").asString())
		.as(StepVerifier::create)
		.expectNext("That's the thing.")
		.expectNext("Updated name.")
		.verifyComplete();

	// Make sure we triggered on insert, one update
	repository.count().as(StepVerifier::create).expectNext(22L).verifyComplete();
}
 
Example #21
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveWithAssignedId(@Autowired ReactiveThingRepository repository) {

	Mono<ThingWithAssignedId> operationUnderTest =
		Mono.fromSupplier(() -> {
			ThingWithAssignedId thing = new ThingWithAssignedId("aaBB");
			thing.setName("That's the thing.");
			return thing;
		}).flatMap(repository::save);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.expectNextCount(1L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> s.run("MATCH (n:Thing) WHERE n.theId = $id RETURN n", parameters("id", "aaBB")).records(),
			RxSession::close
		)
		.map(r -> r.get("n").asNode().get("name").asString())
		.as(StepVerifier::create)
		.expectNext("That's the thing.")
		.verifyComplete();

	repository.count().as(StepVerifier::create).expectNext(22L).verifyComplete();
}
 
Example #22
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void updateSingleEntity(@Autowired ReactivePersonRepository repository) {

	Mono<PersonWithAllConstructor> operationUnderTest = repository.findById(id1)
		.map(originalPerson -> {
			originalPerson.setFirstName("Updated first name");
			originalPerson.setNullable("Updated nullable field");
			return originalPerson;
		})
		.flatMap(repository::save);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.expectNextCount(1L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> {
				Value parameters = parameters("id", id1);
				return s.run("MATCH (n:PersonWithAllConstructor) WHERE id(n) = $id RETURN n", parameters).records();
			},
			RxSession::close
		)
		.map(r -> r.get("n").asNode())
		.as(StepVerifier::create)
		.expectNextMatches(node -> node.get("first_name").asString().equals("Updated first name") &&
			node.get("nullable").asString().equals("Updated nullable field"))
		.verifyComplete();
}
 
Example #23
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveAllIterable(@Autowired ReactivePersonRepository repository) {

	PersonWithAllConstructor newPerson = new PersonWithAllConstructor(
		null, "Mercury", "Freddie", "Queen", true, 1509L,
		LocalDate.of(1946, 9, 15), null, Collections.emptyList(), null, null);

	Flux<Long> operationUnderTest = repository
		.saveAll(Arrays.asList(newPerson))
		.map(PersonWithAllConstructor::getId);

	List<Long> ids = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.recordWith(() -> ids)
		.expectNextCount(1L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> s.run("MATCH (n:PersonWithAllConstructor) WHERE id(n) in $ids RETURN n ORDER BY n.name ASC",
				parameters("ids", ids))
				.records(),
			RxSession::close
		).map(r -> r.get("n").asNode().get("name").asString())
		.as(StepVerifier::create)
		.expectNext("Mercury")
		.verifyComplete();
}
 
Example #24
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveSingleEntity(@Autowired ReactivePersonRepository repository) {

	PersonWithAllConstructor person = new PersonWithAllConstructor(null, "Mercury", "Freddie", "Queen", true, 1509L,
		LocalDate.of(1946, 9, 15), null, Collections.emptyList(), null, null);

	Mono<Long> operationUnderTest = repository
		.save(person)
		.map(PersonWithAllConstructor::getId);

	List<Long> ids = new ArrayList<>();

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.recordWith(() -> ids)
		.expectNextCount(1L)
		.verifyComplete();

	Flux.usingWhen(
		Mono.fromSupplier(() -> createRxSession()),
		s -> s.run("MATCH (n:PersonWithAllConstructor) WHERE id(n) in $ids RETURN n", parameters("ids", ids))
			.records(),
		RxSession::close
	).map(r -> r.get("n").asNode().get("first_name").asString())
		.as(StepVerifier::create)
		.expectNext("Freddie")
		.verifyComplete();
}
 
Example #25
Source File: ReactiveTransactionManagerMixedDatabasesTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void usingSameDatabaseExplicitTx(@Autowired ReactiveNeo4jClient neo4jClient) {
	ReactiveNeo4jTransactionManager otherTransactionManger = new ReactiveNeo4jTransactionManager(driver,
		ReactiveDatabaseSelectionProvider.createStaticDatabaseSelectionProvider(DATABASE_NAME));
	TransactionalOperator otherTransactionTemplate = TransactionalOperator.create(otherTransactionManger);

	Mono<Long> numberOfNodes = neo4jClient.query(TEST_QUERY).in(DATABASE_NAME).fetchAs(Long.class).one()
		.as(otherTransactionTemplate::transactional);

	StepVerifier
		.create(numberOfNodes)
		.expectNext(1L)
		.verifyComplete();
}
 
Example #26
Source File: ReactiveAuditingIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void auditingOfEntityWithGeneratedIdModificationShouldWork(
	@Autowired ImmutableEntityWithGeneratedIdTestRepository repository) {

	Mono<ImmutableAuditableThingWithGeneratedId> findAndUpdateAThing = repository
		.findById(idOfExistingThingWithGeneratedId)
		.flatMap(thing -> repository.save(thing.withName("A new name")));

	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> findAndUpdateAThing)
		.as(StepVerifier::create)
		.consumeNextWith(savedThing -> {

			assertThat(savedThing.getCreatedAt()).isEqualTo(EXISTING_THING_CREATED_AT);
			assertThat(savedThing.getCreatedBy()).isEqualTo(EXISTING_THING_CREATED_BY);

			assertThat(savedThing.getModifiedAt()).isEqualTo(DEFAULT_CREATION_AND_MODIFICATION_DATE);
			assertThat(savedThing.getModifiedBy()).isEqualTo("A user");

			assertThat(savedThing.getName()).isEqualTo("A new name");
		})
		.verifyComplete();

	// Need to happen outside the reactive flow, as we use the blocking session to verify the database
	verifyDatabase(idOfExistingThingWithGeneratedId,
		new ImmutableAuditableThingWithGeneratedId(null, EXISTING_THING_CREATED_AT, EXISTING_THING_CREATED_BY,
			DEFAULT_CREATION_AND_MODIFICATION_DATE, "A user", "A new name"));
}
 
Example #27
Source File: ReactiveAuditingIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void auditingOfModificationShouldWork(@Autowired ImmutableEntityTestRepository repository) {

	Mono<ImmutableAuditableThing> findAndUpdateAThing = repository.findById(idOfExistingThing)
		.flatMap(thing -> repository.save(thing.withName("A new name")));

	TransactionalOperator transactionalOperator = TransactionalOperator.create(transactionManager);
	transactionalOperator
		.execute(t -> findAndUpdateAThing)
		.as(StepVerifier::create)
		.consumeNextWith(savedThing -> {

			assertThat(savedThing.getCreatedAt()).isEqualTo(EXISTING_THING_CREATED_AT);
			assertThat(savedThing.getCreatedBy()).isEqualTo(EXISTING_THING_CREATED_BY);

			assertThat(savedThing.getModifiedAt()).isEqualTo(DEFAULT_CREATION_AND_MODIFICATION_DATE);
			assertThat(savedThing.getModifiedBy()).isEqualTo("A user");

			assertThat(savedThing.getName()).isEqualTo("A new name");
		})
		.verifyComplete();

	// Need to happen outside the reactive flow, as we use the blocking session to verify the database
	verifyDatabase(idOfExistingThing,
		new ImmutableAuditableThing(null, EXISTING_THING_CREATED_AT, EXISTING_THING_CREATED_BY,
			DEFAULT_CREATION_AND_MODIFICATION_DATE, "A user", "A new name"));
}
 
Example #28
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Test
void saveAllWithAssignedId(@Autowired ReactiveThingRepository repository) {

	Flux<ThingWithAssignedId> things = repository
		.findById("anId")
		.map(existingThing -> {
			existingThing.setName("Updated name.");
			return existingThing;
		})
		.concatWith(
			Mono.fromSupplier(() -> {
				ThingWithAssignedId newThing = new ThingWithAssignedId("aaBB");
				newThing.setName("That's the thing.");
				return newThing;
			})
		);

	Flux<ThingWithAssignedId> operationUnderTest = repository
		.saveAll(things);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.expectNextCount(2L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> {
				Value parameters = parameters("ids", Arrays.asList("anId", "aaBB"));
				return s.run("MATCH (n:Thing) WHERE n.theId IN ($ids) RETURN n.name as name ORDER BY n.name ASC",
					parameters)
					.records();
			},
			RxSession::close
		)
		.map(r -> r.get("name").asString())
		.as(StepVerifier::create)
		.expectNext("That's the thing.")
		.expectNext("Updated name.")
		.verifyComplete();

	// Make sure we triggered on insert, one update
	repository.count().as(StepVerifier::create).expectNext(22L).verifyComplete();
}
 
Example #29
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Test
void updateWithAssignedId(@Autowired ReactiveThingRepository repository) {

	Flux<ThingWithAssignedId> operationUnderTest = Flux.concat(
		// Without prior selection
		Mono.fromSupplier(() -> {
			ThingWithAssignedId thing = new ThingWithAssignedId("id07");
			thing.setName("An updated thing");
			return thing;
		}).flatMap(repository::save),

		// With prior selection
		repository.findById("id15")
			.flatMap(thing -> {
				thing.setName("Another updated thing");
				return repository.save(thing);
			})
	);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.expectNextCount(2L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> {
				Value parameters = parameters("ids", Arrays.asList("id07", "id15"));
				return s.run("MATCH (n:Thing) WHERE n.theId IN ($ids) RETURN n.name as name ORDER BY n.name ASC",
					parameters).records();
			},
			RxSession::close
		)
		.map(r -> r.get("name").asString())
		.as(StepVerifier::create)
		.expectNext("An updated thing", "Another updated thing")
		.verifyComplete();

	repository.count().as(StepVerifier::create).expectNext(21L).verifyComplete();
}
 
Example #30
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Test
void saveSingleEntityWithRelationships(@Autowired ReactiveRelationshipRepository repository) {

	PersonWithRelationship person = new PersonWithRelationship();
	person.setName("Freddie");
	Hobby hobby = new Hobby();
	hobby.setName("Music");
	person.setHobbies(hobby);
	Club club = new Club();
	club.setName("ClownsClub");
	person.setClub(club);
	Pet pet1 = new Pet("Jerry");
	Pet pet2 = new Pet("Tom");
	Hobby petHobby = new Hobby();
	petHobby.setName("sleeping");
	pet1.setHobbies(singleton(petHobby));
	person.setPets(Arrays.asList(pet1, pet2));

	List<Long> ids = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> repository.save(person).map(PersonWithRelationship::getId))
		.as(StepVerifier::create)
		.recordWith(() -> ids)
		.expectNextCount(1L)
		.verifyComplete();

	try (Session session = createSession()) {

		Record record = session.run("MATCH (n:PersonWithRelationship)"
				+ " RETURN n,"
				+ " [(n)-[:Has]->(p:Pet) | [ p , [ (p)-[:Has]-(h:Hobby) | h ] ] ] as petsWithHobbies,"
				+ " [(n)-[:Has]->(h:Hobby) | h] as hobbies, "
				+ " [(n)<-[:Has]-(c:Club) | c] as clubs",
			Values.parameters("name", "Freddie")).single();

		assertThat(record.containsKey("n")).isTrue();
		Node rootNode = record.get("n").asNode();
		assertThat(ids.get(0)).isEqualTo(rootNode.id());
		assertThat(rootNode.get("name").asString()).isEqualTo("Freddie");

		List<List<Object>> petsWithHobbies = record.get("petsWithHobbies").asList(Value::asList);

		Map<Object, List<Node>> pets = new HashMap<>();
		for (List<Object> petWithHobbies : petsWithHobbies) {
			pets.put(petWithHobbies.get(0), ((List<Node>) petWithHobbies.get(1)));
		}

		assertThat(pets.keySet().stream().map(pet -> ((Node) pet).get("name").asString()).collect(toList()))
			.containsExactlyInAnyOrder("Jerry", "Tom");

		assertThat(pets.values().stream()
			.flatMap(petHobbies -> petHobbies.stream().map(node -> node.get("name").asString())).collect(toList()))
			.containsExactlyInAnyOrder("sleeping");

		assertThat(record.get("hobbies").asList(entry -> entry.asNode().get("name").asString()))
			.containsExactlyInAnyOrder("Music");

		assertThat(record.get("clubs").asList(entry -> entry.asNode().get("name").asString()))
			.containsExactlyInAnyOrder("ClownsClub");
	}
}