我有用户User和GrantedRole实体,它们具有双向的一对多关系。
当我尝试向用户的Set中添加GrantedRole时,没有引发异常,但是当我调试User和GrantedRole对象的变量时,其描述为
调试时可以读取变量的不同字段,但是当我在User中选择角色字段或GrantedRole中的user字段时,将得到与上述相同的描述。
当我进入用户的GrantedRole的集合时,我最终找到以下描述:
我的代码:
public class User {
private Set<GrantedRole> roles = new HashSet<GrantedRole>();
public User() {
super();
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
public Set<GrantedRole> getRoles() {
return roles;
}
public void setRoles(Set<GrantedRole> roles) {
this.roles = roles;
}
// equals and hashCode are based on username
// toString is based on all fields
}
public class GrantedRole {
private user user;
public GrantedRole() {
super();
}
public GrantedRole(User user, Role role, Organization organization) {
this.user = user;
this.role = role;
this.organization = organization;
}
@ManyToOne
@NotNull
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
// equals and hashCode are based on all fields
// toString was based on all fields, I've changed it to not include User.
}
public class Test {
public void testStuff() {
User user = new User("name");
GrantedRole role = new GrantedRole(user, "role"); //this sets the user field
user.getRoles().add(role); //doesn't throw Exception, but debugging shows InvocationTargetException and StackOverflowException
System.out.println(user.getRoles()); //throws StackOverflowException, as I would expect
}
}
据我了解,我应该能够以这种方式建立双向关系。我阅读了多个教程like this one,但我看不出我在做些什么来导致.add(role)出错。
我遗漏了一些琐碎的代码,如果需要的话,我会很乐意提供。我没有编写代码来确保该用户引用了带有对用户的引用的GrantedRole作为返回,但是我认为这与我遇到的问题无关。
最佳答案
因此,我只是很笨,在toString()方法中进行了递归调用。
User.toString()尝试打印角色,GrantedRole.toString()尝试打印用户。
我通过更改GrantedRole.toString()来打印user.getUsername()来解决此问题,从而打破了这一周期。
关于java - JPA/Hibernate双向多对一结果在StackOverflowException中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17195116/