Query query = session.createQuery("from User u order by u.name asc");The call to setMaxResults(10) limits the query resultset to the first 10 objects (rows) returned by the database.
query.setMaxResults(10);
In this Criteria query, the requested page starts in the middle of the resultset:
Criteria crit = session.createCriteria(User.class);Starting from the fortieth object, you retrieve the next 20 objects.
crit.addOrder( Order.asc("name") );
crit.setFirstResult(40);
crit.setMaxResults(20);
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