我正在努力寻找如何在春季从@ManyToMany关系中检索数据。我遇到了无限递归问题,并尝试了一些解决方案,例如使用@JsonIgnoreProperties,但无济于事。
一个用户可以有多个组,一个组可以有多个用户。我可以将用户添加到组中,但是当检索与用户关联的所有组时,无限递归会导致堆栈溢出。
我的GroupAccount类:
@Entity
public class GroupAccount {
//Private variables omitted for brevity
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "groupAccount_users",
joinColumns = {@JoinColumn(name = "groupAccount_id")},
inverseJoinColumns = {@JoinColumn(name = "user_id")})
private List<User> groupMembers = new ArrayList<>();
//Constructors, most getters, setters omitted for brevity
public void addUserToGroupParticipants(User user){
groupMembers.add(user);
incrementGroupMembers();
}
public void incrementGroupMembers() {
numberOfMembers++;
}
public List<User> getGroupMembers(){
return groupMembers;
}
}
我的用户类别:
@Entity
public class User {
//Private variables omitted for brevity
@ManyToMany(mappedBy="groupMembers",
fetch = FetchType.LAZY)
private List<GroupAccount> groupAccounts = new ArrayList<>();
//Constructors, most getters, setters omitted for brevity
public List<GroupAccount> getUsersAccounts() {
return groupAccounts;
}
}
理想情况下,我希望能够发送具有用户ID的get请求,然后检索与该用户关联的所有GroupAccount对象。接下来,我将希望能够查看与特定GroupAccount关联的所有用户
答案 0 :(得分:0)
您应该在@JsonIgnore
上使用groupMembers
注释,以避免陷入无限递归。
@ManyToMany(fetch = FetchType.LAZY)
@JsonIgnore
@JoinTable(name = "groupAccount_users",
joinColumns = {@JoinColumn(name = "groupAccount_id")},
inverseJoinColumns = {@JoinColumn(name = "user_id")})
private List<User> groupMembers = new ArrayList<>();
答案 1 :(得分:0)
您必须重写User类中的“ toString”方法,对此值的评估会导致堆栈溢出异常。您可以非常轻松地对其进行调试并进行检查。