Video in progress

What happens if you `join fetch` a collection and paginate with `setMaxResults()` at the same time?

@Query("select p from Post p join fetch p.comments order by p.createdAt desc")
Page<Post> findLatest(Pageable pageable);

Hibernate doesn't put LIMIT in the SQL: it loads all the rows, paginates in memory, and logs the HHH90003004 warning. You don't notice it on a small table, but on a big one memory and time blow up.

📖 Answer

The reason is logical: with join fetch, one post is split into several rows (one per comment). LIMIT 20 in SQL returns 20 rows, not 20 posts, so the last post would be left with only half of its comments. That's why Hibernate sends the SQL without a limit and cuts the result in memory.

This is what shows up in the log:

HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory

On prod it's useful to turn this into an error:

spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true

The right way is two steps:

@Query(value = "select p.id from Post p order by p.createdAt desc",
       countQuery = "select count(p) from Post p")
Page<Long> findLatestIds(Pageable pageable);

@Query("select distinct p from Post p left join fetch p.comments where p.id in :ids")
List<Post> findWithComments(@Param("ids") List<Long> ids);

First you get the ids with a proper LIMIT, then you load the collection for those ids (you'll need to restore the order in Java). Or you don't fetch the collection at all and rely on @BatchSize / default_batch_fetch_size, which is also handled with a few IN queries.