Hibernate / Hibernate 7 Basics Interview Questions
What is key-based pagination in Hibernate 7 and how does it differ from offset pagination?
Traditional offset pagination (LIMIT N OFFSET M) gets slower on deep pages. Key-based pagination uses a WHERE clause on the last key value, making each page O(1) regardless of depth.
// OFFSET PAGINATION (gets slower at depth): List<Product> page1000 = session .createQuery("FROM Product ORDER BY id ASC", Product.class) .setFirstResult(19_980) // DB must scan and skip 19,980 rows! .setMaxResults(20) .getResultList(); // HIBERNATE 7: Key-based pagination (O(1) at any depth) import org.hibernate.query.KeyedPage; import org.hibernate.query.KeyedResultList; // First page: KeyedResultList<Product> page = session .createQuery("FROM Product", Product.class) .getKeyedResultList( KeyedPage.firstPage(20, Order.asc(Product_.id)) ); List<Product> products = page.getResultList(); // Next page (use key from previous result): if (page.getNextPage() != null) { KeyedResultList<Product> next = session .createQuery("FROM Product", Product.class) .getKeyedResultList(page.getNextPage()); } // Generated SQL: WHERE id > :lastId ORDER BY id ASC LIMIT 20
More Related questions...