I have the following hibernate entity:
@Entity
public class Customer {
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Address> addresses = new ArrayList<>();
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Contact> contacts = new ArrayList<>();
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Name> names = new ArrayList<>();
// Many more, including a primary key
}
Starting the application, I got the following exception:
org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
If I remove one arbitary OneToMany
association, or if I add a @Fetch(value = FetchMode.JOIN)
to an arbitary OneToMany
association, everything works fine.
Is this a hibernate bug, a hibernate limitation, or is there anything wrong with my entity? TIA!
It is not a bug. It is because of Hibernate uses a one select with a join to fetch all the data. Hibernate can join three and more tables, but the result of joining will have duplicates of, for example, Address
columns. Hibernate needs to remove duplicates — it is a reason why Set
works.
Possible workarounds:
Set<Address>
instead of List<Address>
. You should use Set
for all collections.fetch = FetchType.LAZY
@Fetch(value = FetchMode.SUBSELECT)
Some additional reading: