Home Hibernate Examples Criteria Hibernate Criteria Count Distinct

Ask Questions?

View Latest Questions


 
 

Hibernate Criteria Count Distinct
Posted on: April 7, 2011 at 12:00 AM
Advertisement
In this tutorial you will learn how to count distinct row in a database table

Hibernate Criteria Count Distinct

The Hibernate Criteria count distinct is used to count the number of distinct records in a table. Following a way to use it in a program

Criteria criteria = session.createCriteria(Student.class);
	ProjectionList projList = Projections.projectionList();
	projList.add(Projections.countDistinct("name"));
	criteria.setProjection(projList);
	List list=criteria.list();

An Example of counting distinct record in an application is given below -

CriteriaCountDistinct.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.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

public class CriteriaCountDistinct{
	public static void main(String []args){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Criteria criteria = session.createCriteria(Student.class);
		ProjectionList projList = Projections.projectionList();
		projList.add(Projections.countDistinct("name"));
		criteria.setProjection(projList);
		List list=criteria.list();
		System.out.println(list.get(0));
	}
}

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

select count(distinct this_.name) as y0_ from student this_
No of Distinct Record is 4

Download Select Source Code

Related Tags for Hibernate Criteria Count Distinct:


DMCA.com