我正在努力找出如何在春季从@ManyToMany 关系中检索数据。我遇到了无限递归问题并尝试了一些解决方案,例如使用@JsonIgnoreProperties,但无济于事。一个用户可以有很多组,一个组可以有很多用户。我可以将用户添加到组中,但是在检索与用户关联的所有组时,我会从无限递归中得到堆栈溢出。我的 GroupAccount 类:@Entitypublic 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 brevitypublic void addUserToGroupParticipants(User user){ groupMembers.add(user); incrementGroupMembers();}public void incrementGroupMembers() { numberOfMembers++;}public List<User> getGroupMembers(){ return groupMembers;}}我的用户类:@Entitypublic 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 brevitypublic List<GroupAccount> getUsersAccounts() { return groupAccounts;}}理想情况下,我希望能够使用用户 ID 发送获取请求,然后检索与该用户关联的所有 GroupAccount 对象。稍后,我将希望能够查看与特定 GroupAccount 关联的所有用户
2 回答
MYYA
TA贡献1868条经验 获得超4个赞
您应该使用@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<>();
添加回答
举报
0/150
提交
取消