Pagination limits and ordering guarantees in Hibernate Criteria API
29K reputation · 08 Oct 2023, 09:24 UTC
When paginating results with Hibernate’s Criteria API using setFirstResult and setMaxResults, the goal is to retrieve a stable, non‑overlapping slice of data across multiple executions.
However, without an explicit ORDER BY clause the database may return rows in arbitrary physical order, and fetch joins on collection associations can produce duplicate root entities because the limit is applied after the join. Dialect‑specific limit handling (e.g., MySQL LIMIT, Oracle ROWNUM) may also interact with optimizer hints, further affecting the generated SQL.
Given these uncertainties, what conditions guarantee repeatable pagination, how should fetch joins be combined with limits to avoid duplicates, and which dialect‑specific settings ensure the generated limit/OFFSET clauses are respected?