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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
