Hibernate Criteria Group By
Posted on: April 8, 2011 at 12:00 AM
In this tutorial you will learn about the Group By feature of Hibernate Criteria

Hibernate Criteria Group By

The Hibernate Criteria Group By is used to display the records in a group on the basis of class properties. You can display records in Group By in a following way

Criteria criteria = session.createCriteria(Student.class);
	ProjectionList projectionList = Projections.projectionList();
	projectionList.add(Projections.property("name"));
	projectionList.add(Projections.groupProperty("course"));
	criteria.setProjection(projectionList);
	List results = criteria.list();

An example of Group By is given below, please consider the example

CriteriaGroupBy.java

package net.roseindia.main;

import java.util.Iterator;
import java.util.List;

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

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

public class CriteriaGroupBy {
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		Criteria criteria = session.createCriteria(Student.class);
		ProjectionList projectionList = Projections.projectionList();
		projectionList.add(Projections.property("name"));
		projectionList.add(Projections.groupProperty("course"));

		criteria.setProjection(projectionList);
		List results = criteria.list();

		Iterator resultIterator = results.iterator();

		Object[] obj = (Object[]) resultIterator.next();
		for (int i = 0; i < obj.length; i++) {
			System.out.print(obj[i] + "\t");
		}

	}
}

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

Hibernate: select this_.name as y0_, this_.course as y1_ from student this_ group by this_.course
Raman B.Tec

Download Complete Source Code

Related Tags for Hibernate Criteria Group By:

Advertisements

Ads

 
Advertisement null

Ads