Hibernate Criteria setMaxResults() Function
In this section, you will learn about Hibernate criteria setMaxResults() function with running example and its output. In hibernate criteria, we can use the setMaxResults() function for getting or retriving the maximum selected results.
setMaxResults() function use with criteria object. This function takes a integer type parameter which specified to maximum selected records in result.
In the following example, you will see how to use hibernate setMaxResults() function with hibernate criteria. Here we use setMaxResults(5) means we will get only 5 records of employees.
This criteria.setMaxResults(5) generates the following SQL statement:
Hibernate: select this_.emp_id as emp1_0_0_, this_.emp_name as emp2_0_0_, this_.emp_sal as emp3_0_0_, this_.emp_expences as emp4_0_0_ from employee this_ limit ?
Criteria Main Class: CriteriaSetMaxResultsExample.java
package developerhelpway.hibernate.criteria;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import developerhelpway.hibernate.Employee;
public class CriteriaSetMaxResultsExample {
/**
* @param args
*/
public static void main(String[] args) {
Session sess = null;
try{
SessionFactory sf = new Configuration().
configure().buildSessionFactory();
sess = sf.openSession();
Transaction tr = sess.beginTransaction();
Criteria criteria = sess.createCriteria(
Employee.class);
criteria.setMaxResults(5);
List<Employee> employees = criteria.list();
System.out.println("Get Max 5 Employees:");
for(Employee emp: employees){
System.out.println(
"Id: " + emp.getEmpId()
+ ", EmpName: " + emp.getEmpName()
+ ", EmpSal: " + emp.getEmpSal()
);
}
tr.commit();
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(sess != null){
sess.close();
}
}
}
}
|
Download Code:
employee table:
OutPut:
