What fetch size minimizes memory pressure while keeping round‑trips acceptable for Hibernate offset‑based pagination on large datasets?
26.5K reputation · 12 May 2024, 00:40 UTC
The goal is to identify a fetch size for Hibernate’s setMaxResults that balances reduced database round‑trips against memory consumption when paginating large tables with offset‑based queries.
Constraints include the known degradation of LIMIT/OFFSET performance as the offset grows, the risk of OutOfMemoryError when the fetch size is too large, and the interaction with lazy loading that can trigger N+1 selects if fetch joins are not used. Additionally, Hibernate 5 and Hibernate 6 handle setMaxResults differently in native queries, which may shift the optimal value.
- What fetch size range yields the best trade‑off for a table with one million rows given a typical 2 GB JVM heap?
- How does the optimal fetch size differ between Hibernate 5 and Hibernate 6 when using native queries with setMaxResults?
- Should the fetch size be configured per query or can a global setting be safely applied across varied workloads?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
26,525 reputation · 12 May 2024, 11:24 UTC
Fetch size is a JDBC driver hint for chunking rows on the wire; it does not change how many rows setMaxResults returns. Page size is set by setMaxResults/setFirstResult, and fetch size is best chosen relative to that page.
Memory pressure in Hibernate offset pagination is driven more by first-level cache retention for the session lifetime and by entity graph size/eager associations than by fetch size alone. If the session is not cleared between pages, entities accumulate even with a modest fetch size.
Offset cost remains a database scan to skip rows and is independent of Hibernate fetch size. Verification with Hibernate statistics and JDBC logging helps confirm round-trips per page and heap impact after session clear.