Home Hibernate Examples Criteria Hibernate Criteria Distinct

Ask Questions?

View Latest Questions


 
 

Hibernate Criteria Distinct
Posted on: April 5, 2011 at 12:00 AM
Advertisement
In this tutorial you will learn about the Hibernate Criteria Distinct API

Hibernate Criteria Distinct

The Hibernate Criteria Distinct API search and display the distinct result

Consider the following SQL

SELECT DISTINCT name FROM student WHERE roll_no=2;

The above SQL will return the  distinct name from the student table. The same thing can be written using Criteria distinct API as follows

Criteria criteria = session.createCriteria(Student.class);
	criteria.add(Restrictions.eq("rollNo",2));
	criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        List list = criteria.list();

Consider the example given below

DistinctCriteria.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.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class DistinctCriteria {

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

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

		Object object;

		try {
			// Creating a Criteria instance

			Criteria criteria = session.createCriteria(Student.class);
			System.out.println("\n");
			criteria.add(Restrictions.eq("rollNo",2));
		    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		    List list = criteria.list();
			Iterator itr = list.iterator();
		    
			if (list.size() == 0) {
				System.out.println("No Result Found !");
			}
			while (itr.hasNext()) {
				object = (Object) itr.next();
				System.out.printf("\t");
				System.out.println(((Student) object).getRollNo()+"\t"+ ((Student) object).getName()+"\t"+ ((Student) object).getCourse()+"\t"+ ((Student) object).getAddress());
				}

		} catch (HibernateException e) {

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

	}
}

When you run this application it will display message as shown below:
select this_.roll_no as roll1_0_0_, this_.name as name0_0_, this_.course as course0_0_, this_.address as address0_0_ from student this_ where this_.roll_no=?
2 Raman B.Tec Lucknow

Download Complete Source Code

Related Tags for Hibernate Criteria Distinct:


DMCA.com