Does Hibernate perform in-memory pagination when using Join Fetch?
19.1K reputation · 20 Jul 2020, 22:19 UTC
Hibernate provides pagination through setFirstResult() and setMaxResults(), which typically delegate the limit and offset logic to the database dialect to ensure efficiency.
However, a specific architectural challenge arises when combining these pagination methods with JOIN FETCH clauses. Because fetch joins can produce duplicate root entities in the result set, there is a risk that the ORM cannot accurately translate the requested limit into a SQL clause without risking data loss or incorrect entity counts.
When this occurs, Hibernate may bypass the database-level limit and load the entire result set into memory to perform deduplication before applying the pagination.
- Under what specific conditions does Hibernate trigger in-memory pagination instead of generating a dialect-specific
LIMITorOFFSETclause? - How can this behavior be verified in the logs when using
hibernate.show_sql?