
How to find minimum value in Hibernate criteria query using Projection?

You can find out minimum value in hibernate criteria by using projection. Projection is an interface and a class in ?org.hibernate.criterion?. For using Projection object in our Criteria, we have to call setProjection method.
Example:
package net.roseindia.projection;
import java.util.*;
import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
public class ProjectionMin{
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Criteria criteria=session.createCriteria(Employee.class);
criteria.setProjection(Projections.min("salary"));
List employeeList = (List)criteria.list();
for(Object employee: employeeList){
System.out.println(employee);
}
}
}
Output:
Hibernate: select min(this_.salary) as y0_ from employee this_ 15000
Description: Here we are finding the minimum salary of employee by using
criteria.setProjection(Projections.min("salary"));
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.