Paging Through the Result Set in Hibernate

By: Sumit Pal Viewed: 177 times  Printer Friendly Format    


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

query.setFirstResult(1);

query.setMaxResults(2);

List results = query.list();

displayProductsList(results);

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.



Most Viewed Articles (in Hibernate )

Latest Articles (in Hibernate)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. I have a HSQL query that uses many tables and I'm
View Tutorial          By: Kris Reid at 2009-11-04 15:23:40

2. Hi Along with your provided code below, if we are
View Tutorial          By: Roshan at 2011-05-02 12:06:27

3. can u give me the structure of displayProductList(
View Tutorial          By: swapnil at 2011-09-22 04:41:24

4. i have to retrieve data from database which is on
View Tutorial          By: abhishek at 2012-04-05 05:04:01

5. After coming to second page again I want to go to
View Tutorial          By: Bhagi at 2012-09-23 06:25:54

6. Brettkip
View Tutorial          By: Brettkip at 2017-06-06 03:31:50

7. nfyuphCep
View Tutorial          By: nvcmeqCep at 2017-09-13 06:01:39