Pagination

Paginating through search data is a very common functionality in most enterprise applications. Luckily, Hibernate provides several ways of paginating through the data. One efficient way of doing this is by using the criteria objects that were discussed earlier.

Usually, pagination is accompanied by sorting the search results. The following example shows how this is done using the criteria API:

Criteria criteria = session.createCriteria(Person.class);
List<Person> persons = criteria
  .addOrder(Order.asc("lastname"))
  .setFirstResult(75)
  .setMaxResults(20)
  .list();

Hibernate (actually, the database dialect) composes the SQL to limit the result set to your max result, starting from the offset:

select <columns> from Person this_ left outer join ...

Get Mastering Hibernate now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.