简体   繁体   中英

Bidirectional Relationships in Spring Data Neo4j

I'm trying to create a System to keep track of some courses in my school. There are courses with multiple students and multiple teachers. Students and teachers are represented as Users.

@Node
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {

 @Id
 @GeneratedValue(generatorClass = GeneratedValue.UUIDGenerator.class)
 private UUID id;

 private String name;
 private String password;
 private UserType type;

 @Relationship(type = "ATTENDS", direction = OUTGOING)
 private School school;

 @Relationship(type = "IN_COURSE", direction = OUTGOING)
 private Collection<Course> courses;

 @Relationship(type = "TEACHES", direction = OUTGOING)
 private Collection<Course> teaches;

 public enum UserType {
    STUDENT,
    TEACHER;
 }

}

@Node
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Course {

 @Id
 @GeneratedValue(generatorClass = GeneratedValue.UUIDGenerator.class)
 private UUID id;

 private String name;

 @Relationship(value = "TEACHES", direction = INCOMING)
 private User teacher;
}

Problem When I try to fetch a User, I get a StackOverflowException back.

How can I fix this?

I tried to remove the Relationship on the Course Class and it worked. But in the Course Object in the Response where the same user. In the user was the course and so on.

Spring Data Neo4j detects such cycles like User <> Course and issues cascading MATCH queries driven by the data it receives. If nothing is left to load because a) there is nothing or b) was already visited, it completes. There is no known scenario where this could run into a StackOverflow .

My assumption is that you are running a web application and the output format is JSON. So the problem is based in the JSON mapper because it follows each linked property (until you are running into the overflow). To avoid this, you should add @JsonManagedReference , @JsonIdentityInfo , or @JsonIgnore to your entities where it makes sense for your use-case.

We have this hint as part of another mapping library but the same things apply https://neo4j.com/docs/ogm-manual/current/reference/#_a_note_on_json_serialization

A more in-depth view, also with a more differentiating approach was written by my colleague, Michael. https://gist.github.com/michael-simons/04807990778a10a233e55bb7a2f6d6bc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM