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 Address addresses_ on this_.id=addresses_.person_id order by this_.lastname asc limit ? offset ?
It is important to know that different database engines implement limit
differently. The performance of your query can be impacted if the database doesn't stop processing the rows after the max result has been reached.
3.144.39.144