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.