Wednesday, March 19, 2008

Hibernate Pagination

A commonly used technique is pagination. Users may see the result of their search request (for example, for specific Items) as a page. This page shows a limited subset (say, 10 Items) at a time, and users can navigate to the next and previous pages manually. In Hibernate, Query and Criteria interfaces support this pagination of the query result:
Query query = session.createQuery("from User u order by u.name asc");
query.setMaxResults(10);
The call to setMaxResults(10) limits the query resultset to the first 10 objects (rows) returned by the database.

In this Criteria query, the requested page starts in the middle of the resultset:
Criteria crit = session.createCriteria(User.class);
crit.addOrder( Order.asc("name") );
crit.setFirstResult(40);
crit.setMaxResults(20);
Starting from the fortieth object, you retrieve the next 20 objects.
Note that there is no standard way to express pagination in SQL—Hibernate knows the tricks to make this work efficiently on your particular database. You can even add this flexible pagination option to an SQL query. Hibernate will rewrite your SQL for pagination:
Query sqlQuery = session.createSQLQuery("select {u.*} from USERS {u}").addEntity("u", User.class);
sqlQuery.setFirstResult(40);
sqlQuery.setMaxResults(20);


You may use the method-chaining coding style (methods return the receiving object instead of void) with the Query and Criteria interfaces, rewriting the two previous examples as follows:
Query query = session.createQuery("from User u order by u.name asc").setMaxResults(10);
Criteria crit = session.createCriteria(User.class)
.addOrder( Order.asc("name") )
.setFirstResult(40)
.setMaxResults(20);

-- excerpted from Java.Persistence.with.Hibernate

No comments:

Post a Comment