Hibernate Criteria Aggregate Functions
Posted on: April 6, 2011 at 12:00 AM
In this tutorial you will learn about Aggregate function of hibernate criteria api

Hibernate Criteria Aggregate Functions

The Hibernate Criteria Aggregate Function Supports the following function

min(), max(), sum(), avg(), count(). These functions are of Projections class. Following are the way to use these function in Hibernate Criteria.

Criteria criteria = session.createCriteria(Student.class);
	criteria.setProjection(Projections.max("rollNo"));
	List list = criteria.list();
	System.out.println("Max Roll No is = " + list.get(0));

The above code will get the maximum roll no from the student table

An example of such is given below -

SampleInterfaceImp.java

package net.roseindia.main;

import java.util.List;

import net.roseindia.bean.Student;
import net.roseindia.util.HibernateUtil;

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

public class AggegateFunction {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {

		Session session = HibernateUtil.getSessionFactory().openSession();

		Object object;

		try {
			// Max Projection
			Criteria criteria = session.createCriteria(Student.class);
			criteria.setProjection(Projections.max("rollNo"));
			List list = criteria.list();
			System.out.println("Max Roll No is = " + list.get(0));

			// Min Projection
			Criteria criteriaMin = session.createCriteria(Student.class);
			criteriaMin.setProjection(Projections.min("rollNo"));
			List minList = criteriaMin.list();
			System.out.println("Minimum Roll No is = " + minList.get(0));

			// rowCount Projection
			Criteria criteriaRowCount = session.createCriteria(Student.class);
			criteriaRowCount.setProjection(Projections.rowCount());
			List rowCountList = criteriaRowCount.list();
			System.out.println("Total No of Student is = " + rowCountList.get(0));

			
		} catch (HibernateException e) {

			e.printStackTrace();
		} finally {
			session.close();
		}

	}
}

When you run this application it will display message as shown below:

Hibernate: select max(this_.roll_no) as y0_ from student this_
Max Roll No is = 6
Hibernate: select min(this_.roll_no) as y0_ from student this_
Minimum Roll No is = 1
Hibernate: select count(*) as y0_ from student this_
Total No of Student is = 6

Download Select Source Code

Related Tags for Hibernate Criteria Aggregate Functions:

Advertisements

Ads

Ads

 
Advertisement null

Ads