Hibernate Aggregrate Function AVG
In this section, you will learn about Hibernate AVG aggregrate function or aggregrate function AVG. The AVG(property_name) function takes a parameter as property_name.
The AVG function gives you the average of records of given property in your selected result. The hibernate aggregrate avg function calculate the sum of selected column according to conditions. After that count the records and devide. After divided you will get a result which is agerage of records.
Formulla of averagge: (a+b+c)/3;
You will see the running example of hibernate aggregrate AVG():
package developerhelpway.hibernate.hql.aggregateFunction;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class AvgAggregateFunction {
/**
* @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();
String hql = "SELECT avg(e.empSal) FROM Employee e";
Query query = sess.createQuery(hql);
List avgResultList = query.list();
System.out.println("AVG of Employee sal: "+
avgResultList != null ? avgResultList.get(0) : 0.0);
tr.commit();
}catch(Exception ex){
ex.printStackTrace();
}finally{
sess.close();
}
}
}
|
Download Code
Employe table:
OutPut:
