Sub topic 10
Fetching collections: pagination and multiple bags
This chapter assumes you know basic JPA mapping, Spring Data repositories, JPQL joins, and the Author and Book model from earlier chapters. You have seen JOIN FETCH remove N+1 queries. Fetching a collection with a join brings two problems of its own: pagination and multiple bags. Both come from the way a SQL join multiplies rows.
Why collection joins behave differently
Joining a @ManyToOne (a book's author) adds columns to each row. The row count stays the same. Joining a @OneToMany (an author's books) repeats the parent row once per child.
Suppose there are three authors. Author 1 has two books, author 2 has three, and author 3 has none. Run select a from Author a left join fetch a.books, and the database returns six rows:
| Row | Author | Book |
|---|---|---|
| 1 | Author 1 | Book A |
| 2 | Author 1 | Book B |
| 3 | Author 2 | Book C |
| 4 | Author 2 | Book D |
| 5 | Author 2 | Book E |
| 6 | Author 3 | none |
Hibernate groups these rows back into three Author objects. The database, though, only counts rows. A LIMIT 2 applied to this result would return Author 1 with both books, and nothing else. The limit would not mean "two authors".
Pagination with a collection fetch join
Consider this repository method:
@Query("select a from Author a left join fetch a.books")
Page<Author> findAllWithBooks(Pageable pageable);Spring Data does not reject it. Hibernate cannot apply LIMIT in SQL without cutting the collections, so it loads every row, builds all the authors in memory, and then takes the requested page from that list. It logs a warning similar to:
HHH90003004: firstResult/maxResults specified with collection fetch; applying in memoryWith 100 000 authors and a page size of 20, you still load every author and every book. The query appears to work in tests with small data and fails in production with memory pressure and slow responses.
Spring Data also tries to run a count query for a Page. Combining join fetch with a derived count query can fail, because a count cannot fetch associations. If you must keep such a query, you have to supply a separate countQuery. The better answer is to avoid it.
The two-step fix: page ids, then fetch
Page the parent ids in SQL, where LIMIT is exact, then load those parents with their collections 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);
}A service combines them:
@Transactional(readOnly = true)
public Page<Author> authorsPage(Pageable pageable) {
Page<Long> idPage = authorRepository.findAuthorIds(pageable);
List<Long> ids = idPage.getContent();
if (ids.isEmpty()) {
return Page.empty(pageable);
}
Map<Long, Author> byId = authorRepository.findWithBooksByIdIn(ids).stream()
.collect(Collectors.toMap(Author::getId, Function.identity()));
List<Author> ordered = ids.stream().map(byId::get).toList();
return new PageImpl<>(ordered, pageable, idPage.getTotalElements());
}Notes on this code:
- The first query is a plain id query. Its
ORDER BYcomes from thePageablesort, and the count query is generated correctly. - The second query has no ordering guarantee. The service reorders the authors by the id list, so the page keeps the order requested.
- The empty check matters. An empty
IN ()list is invalid SQL on some databases. - Total cost is three statements at most: ids, count, and the fetch.
Pagination alternative: batch fetching
If you only need the collection to avoid N+1, you can paginate the parents and let batch fetching load the collections. Set the following:
spring.jpa.properties.hibernate.default_batch_fetch_size=50Then authorRepository.findAll(pageable) loads one page of authors in SQL with a correct LIMIT. When code touches getBooks() on those authors, Hibernate loads the collections for up to 50 authors per statement. A page of 20 authors needs one extra query. This is simpler than the two-step approach, at the price of one more round trip and no single-statement guarantee.
Multiple bags
Hibernate calls an unordered List collection without an index column a bag. A bag allows duplicates and has no identity for its elements. Suppose Author also has awards, mapped as a List<Award>. Now fetch both:
@Query("select a from Author a left join fetch a.books left join fetch a.awards")
List<Author> findAllWithBooksAndAwards();Hibernate fails with org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags. The reason is the shape of the result. Joining two collections produces a Cartesian product per author: an author with 4 books and 3 awards yields 12 rows. Hibernate cannot tell which duplicate rows are genuine duplicates in a bag and which come from the other collection's join, so it refuses.
Bad fixes
Changing both collections to Set makes the exception disappear. This is often the first answer found online, and it hides the real problem. The query still returns 12 rows for 4 books and 3 awards. With larger collections, say 50 books and 40 awards, each author returns 2 000 rows. You have traded an exception for a silent Cartesian product.
Changing the fetch type to EAGER does not help either. It also adds hidden queries to every load of the entity.
Better fixes
- Fetch one collection per query. Within a single transaction, the persistence context holds the same
Authorinstances, so a second query fills in the other collection:
@Query("select distinct a from Author a left join fetch a.books where a.id in :ids")
List<Author> fetchBooks(@Param("ids") List<Long> ids);
@Query("select distinct a from Author a left join fetch a.awards where a.id in :ids")
List<Author> fetchAwards(@Param("ids") List<Long> ids);@Transactional(readOnly = true)
public List<Author> loadWithBooksAndAwards(List<Long> ids) {
List<Author> authors = authorRepository.fetchBooks(ids);
authorRepository.fetchAwards(ids);
return authors;
}The second call ignores its return value on purpose. Its effect is that the awards collection on the already loaded authors is now initialized. Two queries, each with rows equal to one collection's size, replace one query with a product.
- Use batch fetching for the second collection, as in the previous section.
- Use DTO projections when the caller needs flat data, not an entity graph.
Edge cases
distinctand duplicates. In Hibernate 6, entity results from a join fetch are deduplicated automatically. In Hibernate 5 you needdistinct. Writing it is harmless in both versions.- Fetch joins and
wherefilters. A condition on the joined collection, such aswhere b.price > 10, makes the fetchedbookscollection contain only matching books. The entity looks complete but is not. Use a separate filtering query or a DTO if you need a filter. - Nested collections. Fetching
booksand then each book'sreviewsthrough a join fetch multiplies rows at every level. Apply the one-collection-per-query rule at each level. @EntityGraphwith aPageable. An entity graph that includes a collection has the same in-memory pagination behavior as a fetch join. The two-step approach applies.- Single-valued associations are safe. Fetch joining
@ManyToOneor@OneToOnedoes not multiply rows, so it works with pagination. A page of books withjoin fetch b.authoris fine.
Choosing quickly
| Situation | Approach |
|---|---|
| Page of parents, one collection needed | Two-step id paging, or batch fetching |
| Page of parents, several collections needed | Page ids, then one fetch query per collection |
| No pagination, one collection | `JOIN FETCH` or `@EntityGraph` |
| No pagination, several collections | One query per collection |
| Read-only list screen with flat data | DTO projection |
Exercise
A repository method Page<Author> findAll... uses left join fetch a.books and returns correct pages in tests with 10 authors. In production, with 200 000 authors, requests are slow and the heap grows. What is happening, how would you confirm it, and how would you fix it?
Show answer
Hibernate cannot apply LIMIT to a query that fetches a collection with a join, because the join repeats each author once per book. It loads all rows and paginates in memory. You can confirm it by searching the logs for the warning HHH90003004 ("firstResult/maxResults specified with collection fetch; applying in memory") and by checking that the logged SQL has no LIMIT or FETCH FIRST clause. To fix it, page the author ids with a plain query (which gets an exact LIMIT and count), then load those authors with their books through a second query that uses where a.id in :ids, and reorder the results by the id list. Batch fetching with default_batch_fetch_size on a plain paged findAll is a simpler alternative.
Exercise
Why does fetching two List collections with join fetch throw MultipleBagFetchException, and why is changing both to Set a poor fix?
Show answer
Two collection joins produce a Cartesian product per parent (for example 4 books times 3 awards gives 12 rows), and Hibernate cannot reliably separate genuine duplicates in a bag from duplicates caused by the other join. Switching to Set removes the exception but not the product, so the database still returns the multiplied rows and the cost grows with the product of the collection sizes. A better fix is to fetch one collection per query within the same transaction, or to use batch fetching for one of them.