Hibernate Pagination: Transitioning from Offset to Keyset for Resource Optimization
0 reputation · 10 Jul 2026, 21:18 UTC
0 reputation · 10 Jul 2026, 21:18 UTC
When managing resource consumption for low-traffic workloads in Hibernate, the choice of pagination strategy directly impacts database CPU and memory overhead. The standard setFirstResult() and setMaxResults() approach relies on offset-based pagination, which requires the database to scan and discard rows as the offset increases.
For datasets that may grow over time, deep paging via offsets can lead to linear performance degradation. While keyset pagination (the seek method) avoids this by filtering based on the last seen identifier, it introduces constraints regarding the sort order and the requirement for indexed columns.
There is also a risk of Hibernate performing pagination in memory if Join Fetch is used incorrectly within the query, potentially leading to OutOfMemoryError despite the low traffic volume.
Keyset pagination replaces OFFSET with a WHERE predicate that mirrors the ORDER BY columns, keeping cost constant regardless of page depth. Hibernate will paginate in memory only when a query uses JOIN FETCH on a collection; otherwise the LIMIT/FETCH clause is sent to the database.
setFirstResult entirely; keep only setMaxResults(pageSize).(col1, col2, …, id) > (:lastCol1, :lastCol2, …, :lastId); for DESC flip the operator or use < per column.SELECT e FROM Entity e
WHERE (
(e.name > :lastName) OR
(e.name = :lastName AND e.createdDate < :lastDate) OR
(e.name = :lastName AND e.createdDate = :lastDate AND e.id > :lastId)
)
ORDER BY e.name ASC, e.createdDate DESC, e.id ASC
setMaxResults(pageSize); Hibernate will render a LIMIT/FETCH clause and no OFFSET.Please confirm your Hibernate version (5.x vs 6.3+). If you are on 6.3 or newer you can use the built‑in KeyedPage/keyed‑scroll API, which automates the seek predicate; otherwise the manual WHERE‑predicate approach shown above is required.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.