Pagination using Hibernate Criteria api

We can use Hibernate Criteria api’s setFirstResult() and setMaxResult() methods for Pagination.

Currently, we have following 4 records in the Employee table :

hibernate pagination

Example : Pagination using Criteria api

In following example, we use criteria.list() method to retrieve all Employee records from database.

package com.topjavatutorial;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateDemo {

  public static void main(String[] args) {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    SessionFactory factory = configuration.buildSessionFactory();
    Session session = HibernateSessionUtil.getSession();
        
    Criteria criteria = session.createCriteria(Employee.class);
    criteria.setFirstResult(0);
    criteria.setMaxResults(3);
    List<Employee> empList = criteria.list();
    for(Employee employee : empList)
      System.out.println(employee);
    
    session.close();
    factory.close();
  }
}

Output:


Hibernate: 
    select
        this_.id as id1_0_0_,
        this_.age as age2_0_0_,
        this_.name as name3_0_0_ 
    from
        Employee this_ limit ?
Employee{id = 2, name = Nicholas Flammel, age = 101}
Employee{id = 3, name = Ram Kumar, age = 34}
Employee{id = 6, name = Bob Thomas, age = 40}

 

The above example only lists the records that would appear on the first page.

For pagination to work , we would also need to know the total of records.

We can do that using Projections as follows :

    Criteria countCriteria = session.createCriteria(Employee.class);
    countCriteria.setProjection(Projections.rowCount());
    Long count = (Long) countCriteria.uniqueResult();

Output:


Hibernate: 
    select
        count(*) as y0_ 
    from
        Employee this_
Total records : 4


 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags