Sub topic 10
Fetching collections: pagination and multiple bags
This chapter assumes you know JPA entity mapping, Spring Data repositories, and JPQL join fetch. It uses the Author and Book model from earlier chapters. Collection fetch joins fix N+1, but they cause two problems of their own: in-memory pagination and multiple bags.
Why pagination breaks
A join returns one row per child. If an author has three books, the author appears in three rows. SQL LIMIT counts rows, not authors, so Hibernate cannot apply it in the database. It would cut an author's books in half.
Hibernate instead loads every row, groups them into entities in memory, and then applies the page. A query like this triggers that behavior:
@Query("select a from Author a join fetch a.books")
Page<Author> findAllWithBooks(Pageable pageable);Hibernate logs a warning: HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory. On a large table, this loads the whole result set into the heap.
The two-step fix
First, page only the parent ids in SQL. Then load those authors with their books in a second query.
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Query("select a.id from Author a")
Page<Long> findAuthorIds(Pageable pageable);
@Query("select distinct a from Author a left join fetch a.books where a.id in :ids")
List<Author> findWithBooksByIdIn(@Param("ids") List<Long> ids);
}The first query has no join, so LIMIT applies to authors. The second query has a bounded IN list, so the join cannot grow beyond one page. Call them in sequence:
Page<Long> idPage = authorRepository.findAuthorIds(PageRequest.of(0, 20, Sort.by("id")));
List<Author> authors = authorRepository.findWithBooksByIdIn(idPage.getContent());The second query does not guarantee order. If order matters, sort authors by the position of each id in idPage.getContent().
A simpler alternative is batch fetching. Page the authors with a plain query and set hibernate.default_batch_fetch_size. The books load lazily in a few batched queries, and the pagination stays in SQL.
Multiple bags
A bag is a collection without a defined order and without an index column. In Hibernate, an unordered List is a bag. Suppose Author also had a List<Award> awards, and you tried to fetch both:
@Query("select a from Author a join fetch a.books join fetch a.awards")
List<Author> findAllWithEverything();Hibernate throws MultipleBagFetchException: cannot simultaneously fetch multiple bags. Even where it worked, the result would be a Cartesian product. An author with 10 books and 10 awards produces 100 rows.
You have three options:
- Fetch one collection per query. Run one
join fetchfor books and one for awards inside the same transaction. The persistence context merges both into the sameAuthorinstances. - Use batch fetching for the second collection.
- Change the type to
Set. This removes the exception, but the Cartesian product remains, so use it only when the collections are small.
Exercise
A repository method uses join fetch a.books and returns Page<Author>. The log shows HHH90003004. What does it mean, and how do you fix it?
Show answer
Hibernate cannot apply LIMIT to a joined collection result, so it loads all rows and paginates in memory. Fix it by paging author ids in a query without a join, then loading those authors with their books using where a.id in :ids. Alternatively, page the authors with a plain query and enable batch fetching.
Exercise
Why does fetching two List collections in one JPQL query throw MultipleBagFetchException, and how can you avoid it?
Show answer
Hibernate cannot reliably tell duplicate rows from legitimate duplicate elements when two bags come from one joined result. Avoid it by fetching each collection in a separate query within one transaction, or by using batch fetching for one of them.