我有兩個類User &角色。他們有多對多的關係。重寫toString()方法時出現StackOverflow錯誤
在用戶級我已經覆蓋了toString方法在角色類
@Override
public String toString() {
return "User [userId=" + this.userId + ", profileName=" + this.profileName
+ ", firstName=" + this.firstName + ", lastName=" + this.lastName
+ ", email=" + this.email + ", socialEmail=" + this.socialEmail
+ ", accountEnabled=" + this.accountEnabled + ", accountNonExpired="
+ this.accountNonExpired + ", accountNonLocked=" + this.accountNonLocked
+ ", country=" + this.country + ", role=" + this.role + "]";
}
同
@Override
public String toString() {
return "Role [roleId=" + roleId + ", users=" + users + ", role=" + role
+ "]";
}
我獲取從數據庫用戶的詳細信息冬眠
@SuppressWarnings("unchecked")
public User getUser(String name){
List<User> userList = new ArrayList<User>();
Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.profileName = :name or u.socialEmail = :name");
query.setParameter("name", name);
userList = query.list();
if (userList.size() > 0)
return userList.get(0);
else
return null;
}
當流程在休眠方法中進入下面的線
userList = query.list();
它引發出的toString是原因 誰能幫我這個
java.lang.StackOverflowError
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:113)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:415)
at java.lang.StringBuilder.append(StringBuilder.java:132)
at java.lang.StringBuilder.<init>(StringBuilder.java:110)
at com.myapp.model.User.toString(User.java:189)
at java.lang.String.valueOf(String.java:2902)
at java.lang.StringBuilder.append(StringBuilder.java:128)
at java.util.AbstractCollection.toString(AbstractCollection.java:450)
at org.hibernate.collection.PersistentSet.toString(PersistentSet.java:310)
at java.lang.String.valueOf(String.java:2902)
at java.lang.StringBuilder.append(StringBuilder.java:128)
at com.myapp.model.Role.toString(Role.java:67)
以下線的位置堆棧溢出異常是toString方法的用戶類開始
at com.myapp.model.User.toString(User.java:189)
爲什麼'用戶'是角色的一個字段?即使它是,它也不應該在'toString()'方法中,因爲你最終得到一個無限遞歸:'User.toString()'調用'Role.toString()',反之亦然。 – biziclop