In a bidirectional association in JPA/Hibernate, having two entities reference each other can potentially lead to a stack overflow error if not handled correctly, especially when using Lombok's @Data annotation. The @Data annotation generates toString(), equals(), and hashCode() methods, which can cause issues with bidirectional relationships.
Why the Stack Overflow Occurs
The stack overflow occurs because the generated toString(), equals(), and hashCode() methods can end up in an infinite loop. For example:
Entity A references Entity B.
Entity B references Entity A.
When toString() is called on Entity A, it calls toString() on Entity B, which in turn calls toString() on Entity A, and so on, leading to a stack overflow.
Solutions
1. Use @ToString.Exclude and @EqualsAndHashCode.Exclude
By excluding the bidirectional field, you prevent the infinite loop in the toString(), equals(), and hashCode() methods.
2. Manually Implement toString(), equals(), and hashCode()
Conclusion
When using bidirectional associations with Lombok's @Data annotation, it's crucial to prevent infinite recursion in the generated methods. You can achieve this by excluding the bidirectional fields from toString(), equals(), and hashCode() using @ToString.Exclude and @EqualsAndHashCode.Exclude, or by manually implementing these methods to avoid the recursion.
cased by
Person.java
andEazyClass.java
In a bidirectional association in JPA/Hibernate, having two entities reference each other can potentially lead to a stack overflow error if not handled correctly, especially when using Lombok's
@Data
annotation. The@Data
annotation generatestoString()
,equals()
, andhashCode()
methods, which can cause issues with bidirectional relationships.Why the Stack Overflow Occurs The stack overflow occurs because the generated
toString()
,equals()
, andhashCode()
methods can end up in an infinite loop. For example:Entity A references Entity B. Entity B references Entity A. When
toString()
is called on Entity A, it callstoString()
on Entity B, which in turn callstoString()
on Entity A, and so on, leading to a stack overflow.1. Use @ToString.Exclude and @EqualsAndHashCode.Exclude By excluding the bidirectional field, you prevent the infinite loop in the toString(), equals(), and hashCode() methods.
Person.java
EazyClass.java
2. Manually Implement toString(), equals(), and hashCode()
When using bidirectional associations with Lombok's
@Data
annotation, it's crucial to prevent infinite recursion in the generated methods. You can achieve this by excluding the bidirectional fields fromtoString()
,equals()
, andhashCode()
using@ToString.Exclude
and@EqualsAndHashCode.Exclude
, or by manually implementing these methods to avoid the recursion.