Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Hibernate Hibernate criteria query using avg()
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


ratna rathor
Hibernate criteria query using avg()
1 Answer(s)      2 years and 7 months ago
Posted in : Hibernate


How to calculate average in Hibernate criteria query using Projection?


Advertisement
View Answers

June 4, 2012 at 7:48 PM


You can calculate average of any numeric values 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 ProjectionAvg{
    public static void main(String[] args) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        Criteria criteria=session.createCriteria(Employee.class);

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

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

Output-

Hibernate: select avg(this_.salary) as y0_ from employee this_
68750.0

Description: Here we are calculating average of all employee salary by using

criteria.setProjection(Projections.avg("salary"))



Related Tutorials/Questions & Answers:
Advertisements
 

 

 

DMCA.com