Robin McCorkell
Robin McCorkell

Reputation: 764

Neo4j OGM relationship in one entity only

I have two NodeEntity classes, which are to be related in a many-to-one relationship (as in, MANY to one). Let's say many entity A's are related to a single entity B. I want to be able to load entity B with a depth greater than 0, but without loading the many related entity A's, and in fact do not ever need to access an entity A from an entity B.

Is it possible to specify the relationship only on entity A, excluding it from entity B, such that loading an entity B would not load any entity A's, but loading an entity A will load an entity B? I'm concerned about saving the entities afterwards, since I don't want to lose the relationship when saving an entity B.

Upvotes: 0

Views: 312

Answers (1)

nmervaillie
nmervaillie

Reputation: 1270

Yes, you can do this. Check out this test case

@Test
@Transactional
public void shouldNotDeleteUnmappedRelations() throws Exception {

    session.purgeDatabase();
    session.query("CREATE (a1:A) CREATE (a2:A) CREATE (b:B{name:'b'}) CREATE (a1)-[:REL]->(b) CREATE (a2)-[:REL]->(b) RETURN id(b) as id", Collections.emptyMap());

    Collection<B> res = session.loadAll(B.class, new Filters("name", "b"), 0);
    B b = res.iterator().next();
    assertThat(b).isNotNull();

    session.save(b);
    session.clear();

    Collection<A> allA = session.loadAll(A.class);
    assertThat(allA).hasSize(2);
    assertThat(allA).extracting("b").isNotNull();
}

Upvotes: 3

Related Questions