I have a question which I think should be pretty common but I can’t find an answer.
I have 2 objects: Group and User. My classes look something like this:
class Group
{
@ManyToMany(fetch = FetchType.EAGER)
List<User> users;
}
class User
{
@ManyToMany(fetch = FetchType.EAGER)
List<Group> groups;
}
Now, when I try to get a User from the database it brings all its groups and all groups bring all its users and so on. Finally, I’m getting a stackoverflow exception.
How can I solve this issue and still have my bidirectional association and the ability to reach the objects in the lists?
Do you get the same problem if you make one of the sides of your bidirectional assocation the owning side of the association using the
mappedByattribute (that you should use anyway)? Like this:Update: I can’t find any evidence that using
EAGERfetching on both sides of a bidirectional association is forbidden and AFAIK, there is no mention of such a restriction in the Hibernate documentation and / or the JPA specification.Actually, according to this comment from Emmanuel Bernard to a (somehow similar) issue:
For me, the above is pretty clear, Hibernate should be able to handle your mapping (as I mentioned in a comment) and I would be tempted to consider any contradictory behavior as a bug.
If you can provide a test case allowing to reproduce the problem, my suggestion would be to open an issue.