Programming Tutorials

Paging Through the Result Set in Hibernate

By: Sumit Pal in Hibernate Tutorials on 2008-09-19  

Many a times you would need to retrieve a large number of records but on the webpage you would show them in multiple pages. For example, in a tracking application, you want to show a history tracking page, the query would return hundreds or even thousands of records. But the webpage you may want to show fifty records on a page and do a simple previous and next links or show page numbers as links to show fifty records in each page.

Pagination through the result set of a database query is a very common application pattern. Typically, you would use pagination for a web application that returned a large set of data for a query. The web application would page through the database query result set to build the appropriate page for the user. The application would be very slow if the web application loaded all of the data into memory for each user. Instead, you can page through the result set and retrieve the results you are going to display one chunk at a time.

There are two methods on the Query interface for paging: setFirstResult() and setMaxResults(), just as with the Criteria interface. The setFirstResult() method takes an integer that represents the first row in your result set, starting with row 0. You can tell Hibernate to only retrieve a fixed number of objects with the setMaxResults() method. Your HQL is unchanged-you only need to modify the Java code that executes the query.

Query query = session.createQuery("from Product");



List results = query.list();


You can change the numbers around and play with the pagination. If you turn on SQL logging, you can see which SQL commands Hibernate uses for pagination. For the open source HSQLDB database, Hibernate uses top and limit.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Hibernate )

Latest Articles (in Hibernate)