07 July 2010

Hibernate , Paging The Result

nice remedy to common pain , from hibernate :)

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)
;

Querying with HQL and JPA QL

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);




From the bible : JavaPersistanceWithHibernate

No comments: