Issue
I am having this error with Java hibernate many to many relationship:
Infinite recursion (StackOverflowError) (through reference chain:
org.hibernate.collection.internal.PersistentBag[0]-
com.company.nms.models.Group["users"]-
org.hibernate.collection.internal.PersistentBag[0]-
com.company.nms.models.User["groups"]
I have checked the relationship but still having this error.
In my User.java, I have:
@ManyToMany(mappedBy = "users", fetch = FetchType.EAGER)
List<Group> groups = new ArrayList<Group>();
in Group.java, I have:
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = UserConstants.REFERENCE_GROUP_USER,
joinColumns = {@JoinColumn(name = "user_group_id")},
inverseJoinColumns = {@JoinColumn(name = "user_id")}
)
List<User> users = new ArrayList<User>();
The expected result should be many to many relationship between User and Group.
Please help. Thanks
Solution
Produced json has infinite depth because of bidirectional reference. You can limit json's output by using @JsonManagedReference
and @JsonBackReference
annotations:
@ManyToMany(mappedBy = "users", fetch = FetchType.EAGER)
@JsonBackReference
List<Group> groups = new ArrayList<Group>();
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = UserConstants.REFERENCE_GROUP_USER,
joinColumns = {@JoinColumn(name = "user_group_id")},
inverseJoinColumns = {@JoinColumn(name = "user_id")}
)
@JsonManagedReference
List<User> users = new ArrayList<User>();
Or annotate one of them with @JsonIgnore
.
Answered By - Andronicus