Hibernate pagination with collection fetch join: choosing between in-memory pagination, batch fetching, and a two-step ID query
0 reputation · 06 May 2026, 01:31 UTC
0 reputation · 06 May 2026, 01:31 UTC
I have a JPA query (Hibernate 6.x, Spring Data JPA) that fetches a parent entity together with a collection-valued association using join fetch, and the repository method also applies pagination via setFirstResult/setMaxResults (through Pageable). The goal is a page of parent entities with their collections eagerly loaded in as few round trips as possible.
The constraint I am unsure about: with a collection fetch join, Hibernate cannot push LIMIT/OFFSET to the database because each parent row is duplicated per child element, so it falls back to in-memory pagination (warning HHH000104). On a small development dataset this behaves fine, but I do not want production to silently fetch the entire table into memory.
The alternatives I see are: keep the fetch join and accept in-memory pagination, drop the fetch join and rely on @BatchSize with lazy loading, or run a two-step query — paginate parent IDs first, then fetch collections by ID (mindful of database IN-list limits).
Given this, my questions are:
@BatchSize instead of a fetch join, how do I size the batch to balance N+1 risk against memory use?A thoughtful contribution can make all the difference. Be the first to share one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.