HibernateCriteriaAggregate-Projection

HibernateCriteriaAggregate-Projection

How to use aggregate function in order by with Criteria API?

View Answers

June 21, 2012 at 6:58 PM

HQL supports many aggregate functions. max() function returns maximum value of specified field in the table.

min() function returns minimum value of specified field in the table. avg() function returns average of specified field in the table. rowCount() function returns the number of rows of table.

Example:

package net.roseindia.main;

import java.util.List;

import net.roseindia.table.Employee;
import net.roseindia.util.ConnectionUtil;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;

public class MainClass{
    public static void main(String [] args){
        SessionFactory sessionFactory=ConnectionUtil.getSessionFactory();
        Session session=sessionFactory.openSession();


        try{
            Criteria criteria=session.createCriteria(Employee.class);
        //Max Projection

            criteria.setProjection(Projections.max("salary"));
            List list=criteria.list();
            System.out.println("Max salary:-"+list.get(0));

        //Min Projection

            criteria.setProjection(Projections.min("salary"));
            List list1=criteria.list();
            System.out.println("Min salary:-"+list1.get(0));

        //Avg Projection
            criteria.setProjection(Projections.avg("salary"));
            list=criteria.list();
            System.out.println("Average Salary:-"+list.get(0));

        //rowCount Projection
            criteria.setProjection(Projections.rowCount());
            list=criteria.list();
            System.out.println("Number of rows:"+list.get(0));

        }catch (HibernateException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

Output:

Hibernate: select max(this_.emp_salary) as y0_ from employee this_
Max salary:-400000
Hibernate: select min(this_.emp_salary) as y0_ from employee this_
Min salary:-18000
Hibernate: select avg(this_.emp_salary) as y0_ from employee this_
Average Salary:-134000.0
Hibernate: select count(*) as y0_ from employee this_
Number of rows:8









Related Tutorials/Questions & Answers:
HibernateCriteriaAggregate-Projection
HibernateCriteriaAggregate-Projection  How to use aggregate function...(Employee.class); //Max Projection criteria.setProjection...(); System.out.println("Max salary:-"+list.get(0)); //Min Projection

Ads