By: Sumit Pal Emailed: 1728 times Printed: 2341 times
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.
View Tutorial By: Kris Reid at 2009-11-04 15:23:40
View Tutorial By: Roshan at 2011-05-02 12:06:27
View Tutorial By: abhishek at 2012-04-05 05:04:01
View Tutorial By: Bhagi at 2012-09-23 06:25:54
Most Viewed Articles (in Hibernate )
Most Emailed Articles (in Hibernate)