Video in progress

Strong Junior 🐻 Hibernate and JPA

Why does MultipleBagFetchException get thrown when you JOIN FETCH two List collections in one query?

Hibernate treats an unordered, unindexed List as a "bag". If you join two bags in one SQL statement, the result turns into a Cartesian product, and Hibernate can't reliably tell which row belongs to which collection, so it forbids this outright.

📖 Answer

// MultipleBagFetchException: cannot simultaneously fetch multiple bags
select p from Post p
left join fetch p.comments
left join fetch p.tags

If a post has 50 comments and 10 tags, the SQL returns 500 rows for a single post. Even if it worked, it would be very expensive.

Fixes:

  1. Two separate queries. The first loads the posts and comments, the second loads the tags for those same posts. The result of the second query is filled into the same objects in the persistence context:
List<Post> posts = em.createQuery(
    "select distinct p from Post p left join fetch p.comments where p.id in :ids", Post.class)
    .setParameter("ids", ids).getResultList();
em.createQuery(
    "select distinct p from Post p left join fetch p.tags where p in :posts", Post.class)
    .setParameter("posts", posts).getResultList();
  1. Make one of the collections a Set. The exception goes away, but the Cartesian product stays. Many people "fix" it this way and then go hunting for the slowness.

  2. Put @BatchSize on the collections and keep them lazy.

I prefer the first option: two light queries beat one heavy one.