It\'s my first question here on stack, so please be gentle :D
I\'m trying to create hibernate OneToMany relationship. When I try to fetch some data from my DB, I\'m
When i was having this problem i was converting the entity to dto. I then realized i was calling the parent class annotated with onetomany from the bridge class annotated with manytoone. Because the parent already calls the bridge, it became cyclic and the collection recursed. Instead of calling the parent method that populates, i just initialized and populated the parent in the child.
I had a very similar issue. I was using Lombok's @Data
annotation on my model objects to auto-generate getters, setters, and other standard methods. I believe the toString()
method generated by Lombok introduced a circular dependency between my Team
and League
objects. When I tried to get the Set<teams> teams
from my League
object, I got a java.lang.StackOverflowError
because Spring was calling the toString method for logging purposes.
I resolved this by getting rid of Lombok's toString()
method. I replaced the @Data
annotation with Lombok's @Getter
and @Setter
annotations. That way I still could benefit from free getters and setters without getting the toString()
method.
I had similar issue and in my case nothing of this didnt help.
Helped this one approach:
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "order_id")
@Fetch(value = FetchMode.SUBSELECT)
private List<Product> orderLines;
name = "order_id" is a foreign key column from Product table.
And i didnt put anything in Product entity.
Also see: Hibernate throws StackOverflowError when querying
In my case, I was using the @IdClass
annotation on an entity which had a foreign key as part of its primary key:
@IdClass(MyEntity.MyEntityKey.class)
public class MyEntity {
public static class MyEntityKey {
private Foo parent;
private int count;
// Getters, setters, constructor, ...
}
@Id
private Foo parent;
@Id
private int number;
//...
}
Now when loading Foo
and eagerly loading all MyEntity
s, Hibernate was again loading the parent entity Foo
while building the key which resulted in the stack overflow.
I fixed the issue by modelling the id using explicit key properties (i.e. including the keys of Foo in MyEntityKey
rather than just a reference to Foo
) as shown in Composite key handling, using @Idclass annotation in Spring boot java (also applied to Non-Spring Hibernate). In short: Use the @JoinColumns
annotation to specify the relationship between the navigation property (to parent) and the id columns.