简体   繁体   中英

PersistentBag.toString() stackoverflow error while querying the result of HQL query

I am a beginner in Hibernate and was trying to implement one of the HQL queries

Query q= em.createQuery("select p from Person p join p.company c");
        List<Person> l = q.getResultList();
        System.out.println(l.get(0));

When I run the above code I get the below error:

Exception in thread "main" java.lang.StackOverflowError
    at java.lang.StringBuilder.append(Unknown Source)
    at java.lang.StringBuilder.<init>(Unknown Source)
    at hibernate5.testing.onetomany.Person.toString(Person.java:71)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at java.util.AbstractCollection.toString(Unknown Source)
    at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:527)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at hibernate5.testing.onetomany.Company.toString(Company.java:72)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)

However when I comment out the sysout It runs as expected.As per the stack trace it seems to concern with the toString method but I am not sure what is the issue here. Below are the POJOs or the entities

Person

getters and setters


    @Override
public String toString() {
    return "Person [id=" + id + ", name=" + name + ", company=" + company + "]";
}

Company

 getters and setters


        @Override
        public String toString() {
            return "Company [id=" + id + ", name=" + name + ", persons=" + persons + "]";
        }

Can someone please help.

You are facing the problem as Person#toString calls the Company#toString and Company#toString again calls the Person#toSting .

So, what is happening is When Person#toString called it called the below toString definition:

    @Override
public String toString() {
    return "Person [id=" + id + ", name=" + name + ", company=" + company + "]";
}

Now can see that you have contaminated the company also that means your return statement actually becomes "Person [id=" + id + ", name=" + name + ", company=" + company.toString() + "]"; . So, it calls the Company#toString() now look the implementaion of Company#toString() it contains persons object in string concatination.Which again calls Person#toString() , and its goes on still the method stack is overflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM