StackOverflowError Springboot OneToMany BiDirectional Mapping
Why is this happening
This is caused by toString()
method being present in both the classes and forming cyclic dependency. This leads to infinite recursion calls between Account
and Member
's toString() methods.
Consider these 2 simple classes. Lombok's @Data
generates toString method for all fields by default.
class Member {
String name;
Account account;
@Override
public String toString() {
return "Member{" +
"name='" + name + '\'' +
", account=" + account.toString() + //Although string concatenation calls toString() on instance, I thought of adding it to call it out
'}';
}
}
class Account {
String id;
Member member;
@Override
public String toString() {
return "Account{" +
"id='" + id + '\'' +
", member=" + member.toString() + //Although string concatenation calls toString on instance, I thought of adding it to call it out
'}';
}
}
public static void main(String[] args) {
Account account = new Account();
Member member = new Member();
account.id="1";
account.member=member;
member.name ="XYZ";
member.account=account;
System.out.println(account);
}
When you call toString method on one of the classes, say Account
it will in turn call toString
method of Member
and the cycle repeats until you run out of stack memory. Here's the stacktracee:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.StringBuilder.append(StringBuilder.java:136)
at com.javainuse.main.Member.toString(AnotherMain.java:23)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at com.javainuse.main.Account.toString(AnotherMain.java:10)
at java.lang.String.valueOf(String.java:2994)
How can I fix it?
Exclude toString generation for one of the classes from your lombok and that should work.refer this I would recommend not having toString at all for entity classes.
What are the causes?
I don't think I understand. Could you elaborate?