Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags
If you are using Hibernate and you see the error "MultipleBagFetchException: cannot simultaneously fetch multiple bags", it means that you are trying to fetch multiple collections of an entity using a single Hibernate query. This is not allowed because it can cause problems with the Hibernate first-level cache and result in inefficient queries.
To fix this error, you will need to split the query into multiple queries, one for each collection. You can use the join fetch
clause to fetch the collections in separate queries.
For example, consider the following entity with two collections, items
and comments
:
@Entity
public class MyEntity {
@OneToMany(mappedBy = "entity")
private List<Item> items;
@OneToMany(mappedBy = "entity")
private List<Comment> comments;
...
}
To fetch both collections in separate queries, you can use the following HQL:
MyEntity entity = (MyEntity) session.createQuery(
"select e from MyEntity e " +
"join fetch e.items " +
"where e.id = :id")
.setParameter("id", id)
.uniqueResult();
entity.getComments().size(); // triggers another query to fetch the comments collection
This code uses a join fetch
clause to fetch the items
collection and a separate query to fetch the comments
collection.
Alternatively, you can use the subselect
fetching strategy to fetch the collections in a single query, but this can result in inefficient queries with