私はエンティティUserとGrantedRoleに双方向の一対多の関係があります。JPA/Hibernateの双方向多対1結果がStackOverflowExceptionになる
私は、ユーザーに設定するGrantedRoleを追加しようとすると、例外スローがありませんが、私は、ユーザーとGrantedRoleオブジェクトの変数は
com.sun.jdi.InvocationException occurred invoking method.
異なるフィールドを読み込む記述を持っているデバッグデバッグ中に変数を読み取ることができますが、ユーザーまたはGrantedRoleのユーザーフィールドで役割フィールドを選択すると、上記と同じ説明が得られます。私は、ユーザーにGrantedRoleのセットに行くとき は、私は最終的に以下の記述を見つける:
Detail formatter error: An exception occurred: java.lang.StackOverflowError
マイコード:それは私が双方向に設定することができるはず私の理解だった
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(役割)が間違ってしまうように私が何をやっているのか分かりません。
私はいくつかの簡単なコードを省略しました。必要ならば私はそれを喜んで提供します。私は、ユーザへの参照を持つGrantedRoleがそのユーザから参照されることを確実にするコードを作成していませんが、問題は私とは関係がありません。
1.ゲッター/セッターは本当に些細なのですか? 2. 'StackOverflowError'の完全なスタックは何が起こっているのかを理解するのに大いに役立ちます。 –
そして、両方のコンストラクタのコード、 'User(String)'と 'GrantedRole(User、String)'を追加することで、正確に何をしているのかを理解することができます。 – eternay
'toString()'メソッドの再帰呼び出しがあるかもしれません。あなたは 'equals'、' hashCode'などのメソッドを親の子から呼び出さないようにしなければなりません。親からの呼び出しには子だけが関心があります。 –