Hibernate Pagination Example
In this section, you will learn how to add pagination in hibernate query. Hibernate pagination provides you to set records in query according to own requirement. Hibernate gives you following types of methods to set recrods in hibernate query.
- setFirstResult(int startingRecordsFrom): With the help of this method we can set the result in query which is starting from records.
- setMaxResults(int maxRecords): With the help of this method we can set the maximum result in query.
In the following example, we will see the hibernate pagination. Pagination provides us to set max result and starting result in query. After that we will get the a final query which containg records according to setFirstResult() and setMaxResults().
You will see the running example to use hibernate pagingation with setFirstResult and setMaxResults methods.
package developerhelpway.hibernate.hql;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import developerhelpway.hibernate.Employee;
public class PaginationQueryExample {
/**
* @param args
*/
public static void main(String[] args) {
Session sess = null;
try{
SessionFactory sf = new Configuration().
configure().buildSessionFactory();
sess = sf.openSession();
String hql = "FROM Employee";
Query query = sess.createQuery(hql);
query.setFirstResult(2);
query.setMaxResults(4);
List<Employee> employees = query.list();
for(Employee emp: employees){
System.out.println(
"Id: " + emp.getEmpId()
+ ", EmpName: " + emp.getEmpName()
+ ", EmpSal: " + emp.getEmpSal()
);
}
Transaction tr = sess.beginTransaction();
tr.commit();
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(sess != null){
sess.close();
}
}
}
}
|
Download Code:
employee table:

OutPut:
