Search code examples
javahibernateneo4jhibernate-ogm

Hibernate Neo4j create relationships from one class


I am trying to use Hibernate to store family tree information. From what I have seen in the documentation, in order to connect two or more entities, they have to be from different classes. So, in order to create relationships between husband and wife, I would need to have two classes respectively. I think this is pointless because both classes would be identical (keep in mind that the tree can be quite large so I would have a lot of duplicate classes that way).

Is there a way to have a single class, for example Person and do the connections just from that class?

Also, if there is not way to achieve that, how would I connect siblings, for example

(p:Sibling)-[:SIBLING_OF]->(k:Sibling)

when they will both be from same class Sibling?


Solution

  • You can create relationships with entities of the same class the same way you create relationships with entities of different classes.

    You can find an example of the mapping on the Hibernate OGM project sources: https://github.com/hibernate/hibernate-ogm/blob/5.2.0.Alpha1/core/src/test/java/org/hibernate/ogm/backendtck/associations/recursive/TreeNode.java

    and the realtive testcase: https://github.com/hibernate/hibernate-ogm/blob/5.2.0.Alpha1/core/src/test/java/org/hibernate/ogm/backendtck/associations/recursive/RecursiveAssociationsTest.java

    The tests map a tree structure with nodes having a parent node and many children, the mapping of the entity looks like like this:

    @Entity
    public class TreeNode {
    
        @Id
        private String name;
    
        @ManyToOne
        private TreeNode parent;
    
        @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent",
            cascade = CascadeType.ALL, orphanRemoval = true)
        private List<TreeNode> children = new ArrayList<TreeNode>( 3 );
    
        ...
    }
    

    NOTE: Based on your needs, you can create the association using native queries but I wouldn't recommend it. Hibernate OGM becomes unaware of the relationship and problems might occur.