Java Code Examples for org.springframework.transaction.reactive.TransactionalOperator#create()

The following examples show how to use org.springframework.transaction.reactive.TransactionalOperator#create() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 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: 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 17
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Test
void saveAll(@Autowired ReactivePersonRepository repository) {

	Flux<PersonWithAllConstructor> persons = repository
		.findById(id1)
		.map(existingPerson -> {
			existingPerson.setFirstName("Updated first name");
			existingPerson.setNullable("Updated nullable field");
			return existingPerson;
		})
		.concatWith(
			Mono.fromSupplier(() -> {
				PersonWithAllConstructor newPerson = new PersonWithAllConstructor(
					null, "Mercury", "Freddie", "Queen", true, 1509L,
					LocalDate.of(1946, 9, 15), null, Collections.emptyList(), null, null);
				return newPerson;
			}));

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

	List<Long> ids = new ArrayList<>();
	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.recordWith(() -> ids)
		.expectNextCount(2L)
		.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")
		.expectNext(TEST_PERSON1_NAME)
		.verifyComplete();
}
 
Example 18
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Test
void saveEntityWithAlreadyExistingTargetNode(@Autowired ReactiveRelationshipRepository repository) {

	Long hobbyId;
	try (Session session = createSession()) {
		hobbyId = session.run("CREATE (h:Hobby{name: 'Music'}) return id(h) as hId").single().get("hId").asLong();
	}

	PersonWithRelationship person = new PersonWithRelationship();
	person.setName("Freddie");
	Hobby hobby = new Hobby();
	hobby.setId(hobbyId);
	hobby.setName("Music");
	person.setHobbies(hobby);

	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()) {

		List<Record> recordList = session.run("MATCH (n:PersonWithRelationship)"
				+ " RETURN n,"
				+ " [(n)-[:Has]->(h:Hobby) | h] as hobbies",
			Values.parameters("name", "Freddie")).list();

		Record record = recordList.get(0);

		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");

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

		// assert that only one hobby is stored
		recordList = session.run("MATCH (h:Hobby) RETURN h").list();
		assertThat(recordList).hasSize(1);
	}
}
 
Example 19
Source File: ReactiveFirestoreTransactionManagerTest.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void writeTransaction() {

	FirestoreTemplate template = getFirestoreTemplate();

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

	doAnswer(invocation -> {
		CommitRequest commitRequest = invocation.getArgument(0);
		StreamObserver<CommitResponse> streamObserver = invocation.getArgument(1);

		assertThat(commitRequest.getTransaction()).isEqualTo(ByteString.copyFromUtf8("transaction1"));
		assertThat(commitRequest.getWritesList().get(0).getUpdate().getName()).isEqualTo(this.parent + "/testEntities/" + "e2");
		assertThat(commitRequest.getWritesList().get(1).getUpdate().getName()).isEqualTo(this.parent + "/testEntities/" + "e3");
		assertThat(commitRequest.getWritesList().get(2).getDelete()).isEqualTo(this.parent + "/testEntities/" + "e3");

		streamObserver.onNext(CommitResponse.newBuilder().build());

		streamObserver.onCompleted();
		return null;
	}).when(this.firestoreStub).commit(any(), any());

	template.findById(Mono.just("e1"), FirestoreTemplateTests.TestEntity.class)
			.flatMap(testEntity -> template.save(new FirestoreTemplateTests.TestEntity("e2", 100L)))
			.flatMap(testEntity -> template.save(new FirestoreTemplateTests.TestEntity("e3", 100L)))
			.flatMap(testEntity -> template.delete(Mono.just(testEntity)))
			.then()
			.as(operator::transactional)
			.as(StepVerifier::create)
			.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());
}
 
Example 20
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");
	}
}