Slow query response when paginating deep result sets with Hibernate setFirstResult
0 reputation · 07 May 2021, 22:00 UTC
0 reputation · 07 May 2021, 22:00 UTC
When paginating large result sets using Hibernate’s setFirstResult and setMaxResults, response time grows noticeably as the offset increases, even though the underlying table is indexed.
The goal is to retrieve pages of data efficiently while guaranteeing deterministic ordering and accurate row counts. Constraints include avoiding full table scans caused by deep offsets, requiring a stable primary key for cursor‑based approaches, and accounting for version‑specific differences between Hibernate 5 and Hibernate 6 regarding fetch size and second‑level cache interaction.
Uncertainty remains about which pagination technique offers the best trade‑off for a given workload and whether mixing native SQL LIMIT/OFFSET with HQL criteria can introduce inconsistencies.
34775 reputation · 08 May 2021, 04:29 UTC
The slowdown occurs because Hibernate’s setFirstResult/setMaxResults translates to SQL OFFSET/LIMIT. The database must read and discard all rows before the offset, so execution time grows linearly with the page number even when an index exists.
org.hibernate.fetchSize only influences JDBC fetch size, not OFFSET processing. Hibernate 6 retains this behavior but improves second‑level cache interaction when the query result is cacheable.LIMIT/OFFSET with HQL criteria can change the projection or add hidden columns, leading to row‑count mismatches unless the SELECT list is identical.hibernate.generate_statistics=true
hibernate.show_sql=true
EXPLAIN ANALYZE (or DB‑specific equivalent) on the logged SQL with increasing offset values to confirm rising rows read.WHERE id > :lastId ORDER BY id LIMIT :pageSize.createQuery or createCriteria with the WHERE predicate and setMaxResults; do not use setFirstResult.Do you have a guaranteed unique, immutable ordering column (e.g., primary key or a stable composite) that can be used for keyset pagination? If not, the keyset approach may need additional columns or may skip/duplicate rows, changing the recommendation.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.