Creating Relationships in Neo4J using Spring-Data

落爺英雄遲暮 提交于 2019-12-24 14:09:48

问题


I want to create a relationship in neo4j where a Person has a list of friends. I can do this in two ways using spring-data.

a) Create a class Person with a List repesenting friends and annotate the same with @Relationship.

@NodeEntity(label="Person")
public class Person {

    @GraphId
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    @Relationship(type = "FRIEND_WITH")
    List<Person> friends; 
}

b) Create the Person object without any List and create the relationship of "FRIEND_WITH" with Cypher like

@Query "CREATE (a)-[FRIEND_WITH]->(b)"

What are the advantages/disadvanages of both the approaches ?


回答1:


Wherever possible you should manage entities and relationships in your domain model using code, not queries. The advantage of doing it in code is that your domain objects and the graph will remain in sync. The underlying Object Graph Mapper using by SDN does not understand what your queries are doing and so cannot make any changes to your domain model for you. This means that every time you mutate the database using a query, you will potentially need to reload all your objects again.




回答2:


I am adding a second answer because I can't format code in comments, but something like this will work out of the box, and doesn't require any queries.

public class Person {

    private Long id;
    private String name;

    @Relationship(type="FOLLOWS", direction = "OUTGOING")
    private Set<Person> followees = new HashSet<>();

    @Relationship(type="FOLLOWS", direction = "INCOMING")
    private Set<Person> followers = new HashSet<>();

    public void follow(Person p) {
        this.followees.add(p);
        p.followers.add(this);
    }

    public void unfollow(Person p) {
        this.followees.remove(p);
        p.followers.remove(this);
    }
}


来源:https://stackoverflow.com/questions/33461927/creating-relationships-in-neo4j-using-spring-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!