Hibernate criteria query using Max()

What is Hibernate criteria query using Max()?

View Answers

June 4, 2012 at 7:43 PM

You can find out maximum 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. Here is an example:

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 ProjectionMax{
    public static void main(String[] args) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        Criteria criteria=session.createCriteria(Employee.class);

        criteria.setProjection(Projections.max("salary"));
        List employeeList = (List)criteria.list();

        for(Object employee: employeeList){
            System.out.println(employee);
        }
            }
}

Output:

Hibernate: select max(this_.salary) as y0_ from employee this_
220000

Description: Here we are finding the maximum salary of employee by using

criteria.setProjection(Projections.max("salary"));









Related Tutorials/Questions & Answers: