Hibernate Criteria addOrder(Order.asc(field_name)) Function
In this section, you will learn about Hibernate addOrder(Order.asc(field_name)) function with running example and its related output. In hibernate criteria, we can use the addOrder() function for ordering the selected list. addOrder(Order.asc("field_name")) takes a parameter as field_name for sorting the results according to given field.
In the following example you will see how to use hibernate addOrder(Order.asc("field_name")) function in your hibernate criteria application. addOrder() function takes a parameter for sorting the result. Here we use the asc for sorting the result in ascending order.
This criteria.addOrder(Order.asc("field_name")) 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_ order by this_.emp_sal asc
Criteria Main Class: CriteriaAddOrderAscExample.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 org.hibernate.criterion.Order;
import developerhelpway.hibernate.Employee;
public class CriteriaAddOrderAscExample {
/**
* @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.addOrder(Order.asc("empSal"));
List<Employee> employees = criteria.list();
System.out.println("Get Employee order by
salary in ascending order:");
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:
OutPut:
