W3docs

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.

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 causes a Cartesian product in the result set, leading to duplicate rows and severe performance degradation.

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 eagerly load one collection, while allowing the other to load lazily.

For example, consider the following entity with two collections, items and comments:


MyEntity entity = session.createQuery(
    "select e from MyEntity e " +
    "join fetch e.items " +
    "where e.id = :id", MyEntity.class)
    .setParameter("id", id)
    .getSingleResult();

entity.getComments().size(); // triggers another query to fetch the comments collection

This code uses a join fetch clause to fetch the items collection in the first query, and a separate query is triggered when accessing 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 large datasets due to the generated IN clause.