org.neo4j.driver.Session Java Examples

The following examples show how to use org.neo4j.driver.Session. 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: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findNodeWithMultipleLabels(@Autowired MultipleLabelWithAssignedIdRepository multipleLabelRepository) {
	long n1Id;
	long n2Id;
	long n3Id;

	try (Session session = createSession()) {
		Record record = session
			.run("CREATE (n1:X:Y:Z{id:4711}), (n2:Y:Z{id:42}), (n3:X{id:23}) return n1, n2, n3").single();
		n1Id = record.get("n1").asNode().get("id").asLong();
		n2Id = record.get("n2").asNode().get("id").asLong();
		n3Id = record.get("n3").asNode().get("id").asLong();
	}

	assertThat(multipleLabelRepository.findById(n1Id)).isPresent();
	assertThat(multipleLabelRepository.findById(n2Id)).isNotPresent();
	assertThat(multipleLabelRepository.findById(n3Id)).isNotPresent();
}
 
Example #2
Source File: DataRestApplicationTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setupData() throws IOException {
	client = MockMvcBuilders.webAppContextSetup(wac).build();

	try (BufferedReader moviesReader = new BufferedReader(
		new InputStreamReader(this.getClass().getResourceAsStream("/movies.cypher")));
		Session session = driver.session()) {

		session.writeTransaction(tx -> {
			tx.run("MATCH (n) DETACH DELETE n");
			String moviesCypher = moviesReader.lines().collect(Collectors.joining(" "));
			tx.run(moviesCypher);
			return null;
		});
	}

}
 
Example #3
Source File: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
Neo4JSession(Neo4JGraph graph, Session session, Neo4JElementIdProvider<?> vertexIdProvider, Neo4JElementIdProvider<?> edgeIdProvider, boolean readonly) {
    Objects.requireNonNull(graph, "graph cannot be null");
    Objects.requireNonNull(session, "session cannot be null");
    Objects.requireNonNull(vertexIdProvider, "vertexIdProvider cannot be null");
    Objects.requireNonNull(edgeIdProvider, "edgeIdProvider cannot be null");
    // log information
    if (logger.isDebugEnabled())
        logger.debug("Creating session [{}]", session.hashCode());
    // store fields
    this.graph = graph;
    this.partition = graph.getPartition();
    this.session = session;
    this.vertexIdProvider = vertexIdProvider;
    this.edgeIdProvider = edgeIdProvider;
    this.readonly = readonly;
}
 
Example #4
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void loadEntityWithBidirectionalRelationshipFromIncomingSide(@Autowired BidirectionalEndRepository repository) {

	long endId;

	try (Session session = createSession()) {
		Record record = session
			.run("CREATE (n:BidirectionalStart{name:'Ernie'})-[:CONNECTED]->(e:BidirectionalEnd{name:'Bert'}) "
				+ "RETURN e").single();

		Node endNode = record.get("e").asNode();
		endId = endNode.id();
	}

	StepVerifier.create(repository.findById(endId))
		.assertNext(entity -> {
			assertThat(entity.getStart()).isNotNull();
		})
		.verifyComplete();
}
 
Example #5
Source File: ReactiveWebApplicationTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void createMovie() {
	MovieEntity newMovie = new MovieEntity("Aeon Flux", "Reactive is the new cool");
	client.put().uri("/movies").bodyValue(newMovie).exchange()
		.expectStatus().isOk();

	// usually a web test ends here but for completeness we check the database directly
	try (Session session = driver.session()) {
		String tagline = session.run("MATCH (m:Movie{title:'Aeon Flux'}) return m")
			.single()
			.get("m").asNode()
			.get("tagline").asString();

		assertThat(tagline).isEqualTo("Reactive is the new cool");
	}
}
 
Example #6
Source File: ReactiveNeo4jOperationsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveAll() {
	String thing1Name = "testThing1";
	String thing2Name = "testThing2";
	ThingWithGeneratedId thing1 = new ThingWithGeneratedId(thing1Name);
	ThingWithGeneratedId thing2 = new ThingWithGeneratedId(thing2Name);

	StepVerifier.create(neo4jOperations.saveAll(Arrays.asList(thing1, thing2)))
		.expectNextCount(2)
		.verifyComplete();

	try (Session session = driver.session(getSessionConfig())) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("name1", thing1Name);
		paramMap.put("name2", thing2Name);

		Result result = session.run(
			"MATCH (t:ThingWithGeneratedId) WHERE t.name = $name1 or t.name = $name2 return t",
			paramMap);
		List<Record> resultValues = result.list();
		assertThat(resultValues).hasSize(2);
		assertThat(resultValues).allMatch(record ->
			record.asMap(Function.identity()).get("t").get("name").asString().startsWith("testThing"));
	}
}
 
Example #7
Source File: Neo4jConversionsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
static void assertWrite(String label, String attribute, Object t) {

		Value driverValue;
		if (t != null && Collection.class.isAssignableFrom(t.getClass())) {
			Collection<?> sourceCollection = (Collection<?>) t;
			Object[] targetCollection = (sourceCollection).stream().map(element ->
				DEFAULT_CONVERSION_SERVICE.convert(element, Value.class)).toArray();
			driverValue = Values.value(targetCollection);
		} else {
			driverValue = DEFAULT_CONVERSION_SERVICE.convert(t, Value.class);
		}

		try (Session session = neo4jConnectionSupport.getDriver().session()) {
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("label", label);
			parameters.put("attribute", attribute);
			parameters.put("v", driverValue);

			long cnt = session
				.run("MATCH (n) WHERE labels(n) = [$label]  AND n[$attribute] = $v RETURN COUNT(n) AS cnt",
					parameters)
				.single().get("cnt").asLong();
			assertThat(cnt).isEqualTo(1L);
		}
	}
 
Example #8
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveEntityWithSelfReferencesInBothDirections(@Autowired ReactivePetRepository repository) {

	Pet luna = new Pet("Luna");
	Pet daphne = new Pet("Daphne");

	luna.setFriends(singletonList(daphne));
	daphne.setFriends(singletonList(luna));

	StepVerifier.create(repository.save(luna))
		.expectNextCount(1)
		.verifyComplete();

	try (Session session = createSession()) {
		Record record = session.run("MATCH (luna:Pet{name:'Luna'})-[:Has]->(daphne:Pet{name:'Daphne'})"
			+ "-[:Has]->(luna2:Pet{name:'Luna'})"
			+ "RETURN luna, daphne, luna2").single();

		assertThat(record.get("luna").asNode().get("name").asString()).isEqualTo("Luna");
		assertThat(record.get("daphne").asNode().get("name").asString()).isEqualTo("Daphne");
		assertThat(record.get("luna2").asNode().get("name").asString()).isEqualTo("Luna");
	}
}
 
Example #9
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveEntityGraphWithSelfInverseRelationshipDefined(@Autowired ReactiveSimilarThingRepository repository) {
	SimilarThing originalThing = new SimilarThing().withName("Original");
	SimilarThing similarThing = new SimilarThing().withName("Similar");


	originalThing.setSimilar(similarThing);
	similarThing.setSimilarOf(originalThing);
	StepVerifier.create(repository.save(originalThing))
		.expectNextCount(1)
		.verifyComplete();

	try (Session session = createSession()) {
		Record record = session.run(
			"MATCH (ot:SimilarThing{name:'Original'})-[r:SimilarTo]->(st:SimilarThing {name:'Similar'})"
				+ " RETURN r").single();

		assertThat(record.keys()).isNotEmpty();
		assertThat(record.containsKey("r")).isTrue();
		assertThat(record.get("r").asRelationship().type()).isEqualToIgnoringCase("SimilarTo");
	}
}
 
Example #10
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findByPropertyOnRelationshipWithPropertiesAnd(@Autowired ReactivePersonWithRelationshipWithPropertiesRepository repository) {
	try (Session session = createSession()) {
		session.run("CREATE (:PersonWithRelationshipWithProperties{name:'Freddie'})-[:LIKES{since: 2020, active: true}]->(:Hobby{name: 'Bowling'})");
	}

	StepVerifier.create(repository.findByHobbiesSinceAndHobbiesActive(2020, true))
		.assertNext(person -> assertThat(person.getName()).isEqualTo("Freddie"))
		.verifyComplete();

	StepVerifier.create(repository.findByHobbiesSinceAndHobbiesActive(2019, true))
		.verifyComplete();

	StepVerifier.create(repository.findByHobbiesSinceAndHobbiesActive(2020, false))
		.verifyComplete();
}
 
Example #11
Source File: Neo4jOperationsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveAll() {
	String thing1Name = "testThing1";
	String thing2Name = "testThing2";
	ThingWithGeneratedId thing1 = new ThingWithGeneratedId(thing1Name);
	ThingWithGeneratedId thing2 = new ThingWithGeneratedId(thing2Name);
	List<ThingWithGeneratedId> savedThings = neo4jOperations.saveAll(Arrays.asList(thing1, thing2));

	assertThat(savedThings).hasSize(2);

	try (Session session = driver.session(getSessionConfig())) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("name1", thing1Name);
		paramMap.put("name2", thing2Name);

		Result result = session.run(
			"MATCH (t:ThingWithGeneratedId) WHERE t.name = $name1 or t.name = $name2 return t",
			paramMap);
		List<Record> resultValues = result.list();
		assertThat(resultValues).hasSize(2);
		assertThat(resultValues).allMatch(record ->
			record.asMap(Function.identity()).get("t").get("name").asString().startsWith("testThing"));
	}
}
 
Example #12
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findNodeWithMultipleLabels(@Autowired ReactiveMultipleLabelWithAssignedIdRepository repository) {

	long n1Id;
	long n2Id;
	long n3Id;

	try (Session session = createSession()) {
		Record record = session.run("CREATE (n1:X:Y:Z{id:4711}), (n2:Y:Z{id:42}), (n3:X{id:23}) return n1, n2, n3").single();
		n1Id = record.get("n1").asNode().get("id").asLong();
		n2Id = record.get("n2").asNode().get("id").asLong();
		n3Id = record.get("n3").asNode().get("id").asLong();
	}

	StepVerifier.create(repository.findById(n1Id))
		.expectNextCount(1)
		.verifyComplete();
	StepVerifier.create(repository.findById(n2Id))
		.verifyComplete();
	StepVerifier.create(repository.findById(n3Id))
		.verifyComplete();
}
 
Example #13
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findByPropertyOnRelatedEntitiesOr(@Autowired ReactiveRelationshipRepository repository) {
	try (Session session = createSession()) {
		session.run("CREATE (n:PersonWithRelationship{name:'Freddie'})-[:Has]->(:Pet{name: 'Tom'}),"
			+ "(n)-[:Has]->(:Hobby{name: 'Music'})");
	}

	StepVerifier.create(repository.findByHobbiesNameOrPetsName("Music", "Jerry"))
		.assertNext(person -> assertThat(person.getName()).isEqualTo("Freddie"))
		.verifyComplete();
	StepVerifier.create(repository.findByHobbiesNameOrPetsName("Sports", "Tom"))
		.assertNext(person -> assertThat(person.getName()).isEqualTo("Freddie"))
		.verifyComplete();

	StepVerifier.create(repository.findByHobbiesNameOrPetsName("Sports", "Jerry"))
		.verifyComplete();
}
 
Example #14
Source File: DataRestApplicationTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void createMovie() throws Exception {
	client.perform(post("/movies")
		.contentType(MediaType.APPLICATION_JSON)
		.content("{\"title\": \"Aeon Flux\", \"description\": \"Reactive is the new cool\"}"))
		.andExpect(status().isCreated());

	// usually a web test ends here but for completeness we check the database directly
	try (Session session = driver.session()) {
		String tagline = session.run("MATCH (m:Movie{title:'Aeon Flux'}) return m")
			.single()
			.get("m").asNode()
			.get("tagline").asString();

		assertThat(tagline).isEqualTo("Reactive is the new cool");
	}
}
 
Example #15
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void createNodeAndRelationshipWithMultipleLabels(@Autowired ReactiveMultipleLabelWithAssignedIdRepository repository) {

	MultipleLabels.MultipleLabelsEntityWithAssignedId entity = new MultipleLabels.MultipleLabelsEntityWithAssignedId(4711L);
	entity.otherMultipleLabelEntity = new MultipleLabels.MultipleLabelsEntityWithAssignedId(42L);

	repository.save(entity).block();

	try (Session session = createSession()) {
		Record record = session.run("MATCH (n:X)-[:HAS]->(c:X) return n, c").single();
		Node parentNode = record.get("n").asNode();
		Node childNode = record.get("c").asNode();
		assertThat(parentNode.labels()).containsExactlyInAnyOrder("X", "Y", "Z");
		assertThat(childNode.labels()).containsExactlyInAnyOrder("X", "Y", "Z");
	}
}
 
Example #16
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void deleteCollectionRelationship(@Autowired ReactiveRelationshipRepository repository) {
	try (Session session = createSession()) {
		session.run("CREATE (n:PersonWithRelationship{name:'Freddie'}), "
			+ "(n)-[:Has]->(p1:Pet{name: 'Jerry'}), (n)-[:Has]->(p2:Pet{name: 'Tom'})");
	}

	Publisher<PersonWithRelationship> personLoad = repository.getPersonWithRelationshipsViaQuery()
		.map(person -> {
			person.getPets().remove(0);
			return person;
		});

	Flux<PersonWithRelationship> personSave = repository.saveAll(personLoad);

	StepVerifier.create(personSave.then(repository.getPersonWithRelationshipsViaQuery()))
		.assertNext(person -> {
			assertThat(person.getPets()).hasSize(1);
		})
		.verifyComplete();
}
 
Example #17
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void deleteSimpleRelationship(@Autowired ReactiveRelationshipRepository repository) {
	try (Session session = createSession()) {
		session.run("CREATE (n:PersonWithRelationship{name:'Freddie'})-[:Has]->(h1:Hobby{name:'Music'})");
	}

	Publisher<PersonWithRelationship> personLoad = repository.getPersonWithRelationshipsViaQuery()
		.map(person -> {
			person.setHobbies(null);
			return person;
		});

	Flux<PersonWithRelationship> personSave = repository.saveAll(personLoad);

	StepVerifier.create(personSave.then(repository.getPersonWithRelationshipsViaQuery()))
		.assertNext(person -> {
			assertThat(person.getHobbies()).isNull();
		})
		.verifyComplete();
}
 
Example #18
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findNodeWithMultipleLabels(@Autowired MultipleLabelRepository multipleLabelRepository) {
	long n1Id;
	long n2Id;
	long n3Id;

	try (Session session = createSession()) {
		Record record = session.run("CREATE (n1:A:B:C), (n2:B:C), (n3:A) return n1, n2, n3").single();
		n1Id = record.get("n1").asNode().id();
		n2Id = record.get("n2").asNode().id();
		n3Id = record.get("n3").asNode().id();
	}

	assertThat(multipleLabelRepository.findById(n1Id)).isPresent();
	assertThat(multipleLabelRepository.findById(n2Id)).isNotPresent();
	assertThat(multipleLabelRepository.findById(n3Id)).isNotPresent();
}
 
Example #19
Source File: DynamicLabelsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
protected final List<String> getLabels(Condition idCondition, Object id) {

			Node n = Cypher.anyNode("n");
			String cypher = Renderer.getDefaultRenderer().render(Cypher
				.match(n)
				.where(idCondition).and(not(exists(n.property("moreLabels"))))
				.returning(n.labels().as("labels"))
				.build()
			);

			try (Session session = driver.session()) {
				return session
					.readTransaction(tx -> tx
						.run(cypher, Collections.singletonMap("id", id))
						.single().get("labels")
						.asList(Value::asString)
					);
			}
		}
 
Example #20
Source File: CallbacksITBase.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
protected void verifyDatabase(Iterable<ThingWithAssignedId> expectedValues) {

		List<String> ids = StreamSupport.stream(expectedValues.spliterator(), false)
			.map(ThingWithAssignedId::getTheId).collect(toList());
		List<String> names = StreamSupport.stream(expectedValues.spliterator(), false)
			.map(ThingWithAssignedId::getName).collect(toList());
		try (Session session = driver.session()) {
			Record record = session
				.run("MATCH (n:Thing) WHERE n.theId in $ids RETURN COLLECT(n) as things", Values.parameters("ids", ids))
				.single();

			List<Node> nodes = record.get("things").asList(Value::asNode);
			assertThat(nodes).extracting(n -> n.get("theId").asString()).containsAll(ids);
			assertThat(nodes).extracting(n -> n.get("name").asString())
				.containsAll(names);
		}
	}
 
Example #21
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveSingleEntity(@Autowired PersonRepository repository) {

	PersonWithAllConstructor person = new PersonWithAllConstructor(null, "Mercury", "Freddie", "Queen", true,
		1509L,
		LocalDate.of(1946, 9, 15), null, Arrays.asList("b", "a"), null, null);
	PersonWithAllConstructor savedPerson = repository.save(person);
	try (Session session = createSession()) {
		Record record = session
			.run("MATCH (n:PersonWithAllConstructor) WHERE n.first_name = $first_name RETURN n",
				Values.parameters("first_name", "Freddie")).single();

		assertThat(record.containsKey("n")).isTrue();
		Node node = record.get("n").asNode();
		assertThat(savedPerson.getId()).isEqualTo(node.id());
		assertThat(node.get("things").asList()).containsExactly("b", "a");
	}
}
 
Example #22
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findEntityWithSelfReferencesInBothDirections(@Autowired ReactivePetRepository repository) {

	long petId;

	try (Session session = createSession()) {
		petId = session.run("CREATE (luna:Pet{name:'Luna'})-[:Has]->(daphne:Pet{name:'Daphne'})"
			+ "-[:Has]->(luna2:Pet{name:'Luna'})"
			+ "RETURN id(luna) as id").single().get("id").asLong();
	}

	StepVerifier.create(repository.findById(petId))
		.assertNext(loadedPet -> {
			assertThat(loadedPet.getFriends().get(0).getName()).isEqualTo("Daphne");
			assertThat(loadedPet.getFriends().get(0).getFriends().get(0).getName()).isEqualTo("Luna");
		})
		.verifyComplete();
}
 
Example #23
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findEntityWithRelationshipWithAssignedId(@Autowired PetRepository repository) {

	long petNodeId;

	try (Session session = createSession()) {
		Record record = session
			.run("CREATE (p:Pet{name:'Jerry'})-[:Has]->(t:Thing{theId:'t1', name:'Thing1'}) "
				+ "RETURN p, t").single();

		Node petNode = record.get("p").asNode();
		petNodeId = petNode.id();
	}

	Pet pet = repository.findById(petNodeId).get();
	ThingWithAssignedId relatedThing = pet.getThings().get(0);
	assertThat(relatedThing.getTheId()).isEqualTo("t1");
	assertThat(relatedThing.getName()).isEqualTo("Thing1");
}
 
Example #24
Source File: Neo4JSessionWhileAddEdgeTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenEmptyKeyValuePairsShouldCreateEdgeWithId() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(graph.getPartition()).thenAnswer(invocation -> partition);
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    Mockito.when(provider.generate()).thenAnswer(invocation -> 1L);
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    try (Neo4JSession session = new Neo4JSession(graph, Mockito.mock(Session.class), provider, provider, false)) {
        // act
        Neo4JEdge edge = session.addEdge("label1", outVertex, inVertex);
        // assert
        Assert.assertNotNull("Failed to create edge", edge);
        Assert.assertEquals("Failed to assign edge id", 1L, edge.id());
        Assert.assertTrue("Failed to mark edge as transient", edge.isTransient());
    }
}
 
Example #25
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveWithConvertedId(@Autowired EntityWithConvertedIdRepository repository) {
	EntityWithConvertedId entity = new EntityWithConvertedId();
	entity.setIdentifyingEnum(EntityWithConvertedId.IdentifyingEnum.A);
	repository.save(entity);

	try (Session session = createSession()) {
		Record node = session.run("MATCH (e:EntityWithConvertedId) return e").next();
		assertThat(node.get("e").get("identifyingEnum").asString()).isEqualTo("A");
	}
}
 
Example #26
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void updateWithAssignedId(@Autowired ThingRepository repository) {

	assertThat(repository.count()).isEqualTo(21);

	ThingWithAssignedId thing = new ThingWithAssignedId("id07");
	thing.setName("An updated thing");
	repository.save(thing);

	thing = repository.findById("id15").get();
	thing.setName("Another updated thing");
	repository.save(thing);

	try (Session session = createSession()) {
		Record record = session
			.run(
				"MATCH (n:Thing) WHERE n.theId IN ($ids) WITH n ORDER BY n.name ASC RETURN COLLECT(n.name) as names",
				Values.parameters("ids", Arrays.asList("id07", "id15")))
			.single();

		assertThat(record.containsKey("names")).isTrue();
		List<String> names = record.get("names").asList(Value::asString);
		assertThat(names).containsExactly("An updated thing", "Another updated thing");

		assertThat(repository.count()).isEqualTo(21);
	}
}
 
Example #27
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void findByPropertyOnRelationshipWithPropertiesOr(@Autowired PersonWithRelationshipWithPropertiesRepository repository) {
	try (Session session = createSession()) {
		session.run("CREATE (:PersonWithRelationshipWithProperties{name:'Freddie'})-[:LIKES{since: 2020, active: true}]->(:Hobby{name: 'Bowling'})");
	}

	assertThat(repository.findByHobbiesSinceOrHobbiesActive(2020, false).getName()).isEqualTo("Freddie");
	assertThat(repository.findByHobbiesSinceOrHobbiesActive(2019, true).getName()).isEqualTo("Freddie");
	assertThat(repository.findByHobbiesSinceOrHobbiesActive(2019, false)).isNull();
}
 
Example #28
Source File: ReactiveRelationshipsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * This stores multiple, different instances.
 *
 * @param repository The repository to use.
 */
@Test
void shouldSaveMultipleRelationshipsOfSameObjectType(@Autowired MultipleRelationshipsThingRepository repository) {

	MultipleRelationshipsThing p = new MultipleRelationshipsThing("p");
	p.setTypeA(new MultipleRelationshipsThing("c1"));
	p.setTypeB(Collections.singletonList(new MultipleRelationshipsThing("c2")));
	p.setTypeC(Collections.singletonList(new MultipleRelationshipsThing("c3")));

	repository.save(p)
		.map(MultipleRelationshipsThing::getId)
		.flatMap(repository::findById)
		.as(StepVerifier::create)
		.assertNext(loadedThing -> {
			MultipleRelationshipsThing typeA = loadedThing.getTypeA();
			List<MultipleRelationshipsThing> typeB = loadedThing.getTypeB();
			List<MultipleRelationshipsThing> typeC = loadedThing.getTypeC();

			assertThat(typeA).isNotNull();
			assertThat(typeA).extracting(MultipleRelationshipsThing::getName).isEqualTo("c1");
			assertThat(typeB).extracting(MultipleRelationshipsThing::getName).containsExactly("c2");
			assertThat(typeC).extracting(MultipleRelationshipsThing::getName).containsExactly("c3");
		})
		.verifyComplete();

	try (Session session = driver.session()) {

		List<String> names = session.run(
			"MATCH (n:MultipleRelationshipsThing {name: 'p'}) - [r:TYPE_A|TYPE_B|TYPE_C] -> (o) RETURN r, o")
			.list(record -> {
				String type = record.get("r").asRelationship().type();
				String name = record.get("o").get("name").asString();
				return type + "_" + name;
			});
		assertThat(names).containsExactlyInAnyOrder("TYPE_A_c1", "TYPE_B_c2", "TYPE_C_c3");
	}
}
 
Example #29
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveAllWithAssignedId(@Autowired ThingRepository repository) {

	assertThat(repository.count()).isEqualTo(21);

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

	ThingWithAssignedId existingThing = repository.findById("anId").get();
	existingThing.setName("Updated name.");

	repository.saveAll(Arrays.asList(newThing, existingThing));

	try (Session session = createSession()) {
		Record record = session
			.run(
				"MATCH (n:Thing) WHERE n.theId IN ($ids) WITH n ORDER BY n.name ASC RETURN COLLECT(n.name) as names",
				Values.parameters("ids", Arrays.asList(newThing.getTheId(), existingThing.getTheId())))
			.single();

		assertThat(record.containsKey("names")).isTrue();
		List<String> names = record.get("names").asList(Value::asString);
		assertThat(names).containsExactly(newThing.getName(), existingThing.getName());

		assertThat(repository.count()).isEqualTo(22);
	}
}
 
Example #30
Source File: Neo4jTransactionManager.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
	Neo4jTransactionObject transactionObject = extractNeo4jTransaction(transaction);

	TransactionConfig transactionConfig = createTransactionConfigFrom(definition);
	boolean readOnly = definition.isReadOnly();


	TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly);

	try {
		// Prepare configuration data
		Neo4jTransactionContext context = new Neo4jTransactionContext(
			databaseSelectionProvider.getDatabaseSelection().getValue(),
			bookmarkManager.getBookmarks()
		);

		// Configure and open session together with a native transaction
		Session session = this.driver
			.session(sessionConfig(readOnly, context.getBookmarks(), context.getDatabaseName()));
		Transaction nativeTransaction = session.beginTransaction(transactionConfig);

		// Synchronize on that
		Neo4jTransactionHolder transactionHolder = new Neo4jTransactionHolder(context, session, nativeTransaction);
		transactionHolder.setSynchronizedWithTransaction(true);
		transactionObject.setResourceHolder(transactionHolder);

		TransactionSynchronizationManager.bindResource(this.driver, transactionHolder);
	} catch (Exception ex) {
		throw new TransactionSystemException(String.format("Could not open a new Neo4j session: %s", ex.getMessage()));
	}
}