Video in progress
What happens if you fetch a collection with JOIN FETCH and paginate with Pageable?
Hibernate can't put a LIMIT in the SQL because the JOIN multiplies the rows; it pulls the whole result from the database, paginates in memory, and logs the HHH90003004 warning. On a big table this leads to slowness and OutOfMemoryError.
📖 Answer
@Query("select o from Order o join fetch o.items where o.status = :s")
Page<Order> findWithItems(@Param("s") Status s, Pageable p);
If one order has 5 items, the SQL result has 5 rows. With LIMIT 20 you'd get 20 rows (say 4 orders), not 20 orders. So Hibernate drops the LIMIT, loads all matching orders with their items, and cuts out 20 in memory. In the log:
HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory
In Hibernate 6, if you set hibernate.query.fail_on_pagination_over_collection_fetch=true, this situation throws an error; it's useful to turn on in the test environment.
What you can do:
- Two steps: first page only the ids, then fetch by those ids.
Page<Long> ids = orderRepo.findIdsByStatus(s, pageable);
List<Order> orders = orderRepo.findWithItemsByIdIn(ids.getContent());
- Batch fetch: leave the collection lazy and set
@BatchSize(size = 50)orhibernate.default_batch_fetch_size, so the items of 20 orders come in oneIN (...)query. - DTO projection: on a list page, do you really need all the items? Often the count or the sum is enough, and you get it with an aggregate query.
@EntityGraph runs into the same problem, since it also does a JOIN.
Sign up to mark studied questions and save your progress.