重写toString()方法时出现StackOverflow错误

时间:2015-07-02 19:30:44

标签: java hibernate

我有两个班级User&角色。他们有很多关系。

在User类中,我重写了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
            + "]";
}

我是通过hibernate

从db获取用户详细信息
@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; 
    }

当流程在hibernate方法中出现在下面的行

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)

以下行的位置是User class

中toString方法的开头
at com.myapp.model.User.toString(User.java:189)

1 个答案:

答案 0 :(得分:9)

在用户的import Tkinter as tk class Example(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.entry = tk.Entry(self) self.entry.pack(fill="x") self.entry.bind("<w><d>", self.onWD) # alternatively: self.entry.bind("wd", self.onWD) def onWD(self, event): print "boom!" if __name__ == "__main__": root = tk.Tk() Example(root).pack(fill="both", expand=True) root.mainloop() 中,您引用toString(),并在角色role中引用toString()。现在,如果每个角色都有一个用户列表,并且每个用户实例都有一个返回父角色的引用,那么您就有了循环引用。基本上,您的对象图如下所示:

Object graph

所以会发生userstoString()上调用,然后尝试在所有用户上调用role。但它将从toString()开始,其中返回user-1,并且该过程将重新开始。你基本上有一个无限递归的情况。