Does Hibernate paginate JOIN FETCH queries in memory instead of SQL?
0 reputation · 19 Dec 2021, 19:52 UTC
I am designing a paginated endpoint in a Spring application using Hibernate ORM 6.x as the JPA provider, backed by PostgreSQL. The query loads parent entities together with a lazy collection, so I want to combine a JOIN FETCH with setFirstResult() and setMaxResults() on a TypedQuery.
My concern is the interaction between collection fetch joins and pagination. I have read that when a query fetches a collection, Hibernate may not be able to apply row limits in the generated SQL, because limiting rows would truncate the joined children. In that case it allegedly falls back to fetching all matching rows and applying the offset and limit in memory, which would defeat the purpose of pagination for large tables and risk high memory usage in the persistence context.
I would like to confirm the exact behavior before committing to this design, ideally verified against generated SQL with show_sql enabled rather than assumed from documentation summaries.
Specifically:
- Under what conditions does Hibernate 6 perform in-memory pagination for a
JOIN FETCHon a collection, and is a warning logged when this happens? - Does the behavior differ between
List,Set, and bag-mapped collections? - Is splitting the query into an ID-only paginated query plus a second fetch query the accepted way to keep pagination in SQL?