Pagination in Hibernate Query API
Pagination is the very common problem for the most of the eneterprise applications.When we are retrieving thousands of records from the database, it is not good idea to retrieve all the records at the same time. So, we have to implement some sort of pagination concept in your application to restrict the number of rows to be fetched from the database.
Pagination can be done in the middle tier or in the database itself. if you are implementing the pagination in themidd letier, you have to retrieve all the records from the database and store it in the cache. It will take more memory and slow down the performance. So, it is good idea to implement in the database. However, it purely depends on the project requirement.
Hibernate APIs provide few methods to set the pagination citerias in the query. We can use bothe normal Query and Criteria API. Look into the following code for how to create pagination using the Query object:
1 2 3
Query query = session.createQuery("from Studenet s"); query.setFirstResult(25); query.setMaxResults(50);
1 2 3 4
Criteria criteria = session.createCriteria(Student.class); criteria.setFirstResult(25); criteria.setMaxResults(50); List result = criteria.list();
In the above code, both the techniques are telling the Hibernate query for how many records to be retrieved and first set of records. These values can be dynamically changed and we can obtain the pagination implementation.