Pagination in Hibernate Query API

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.

also read:

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:

Query query = session.createQuery("from Studenet s");
query.setFirstResult(25);
query.setMaxResults(50);
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.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Celso Dantas says:

    any ideia to request hibernate to paginate using LIMIT in the database and not doing pagination in memory?

Speak Your Mind

*