Hibernate Criteria Join
Posted on: April 5, 2011 at 12:00 AM
In this tutorial you will learn about the hibernate Criteria join Operation

Hibernate Criteria Join API

Hibernate Criteria JOIN API allows users to perform join operation.

Suppose you have to perform a operation like

SELECT S.*, C.* FROM STUDENT S, CONTACT  C WHERE S.ROLL_NO=C.ID;

Then you can write this statement using Criteria in a very simple way

Criteria criteria = session.createCriteria(Student.class);
criteria.setFetchMode("Contact", FetchMode.JOIN);
List list = criteria.list();

The above statement is very simple, that you have to only call the setFetchMode(ClassName, Type of operation);

In the setFetchMode() method first provide the name of the class, and type of operation on the class.

Suppose you have to apply restriction on join operation such as

SELECT C.*, S.* FROM CONTACT C, STUDENT S WHERE C.ID=S.ROLL_NO AND S.ROLL_NO=?5?;

Then you can write the above statement in criteria as

Criteria criteria = session.createCriteria(Student.class);
	criteria.setFetchMode("Contact", FetchMode.JOIN).add(
			Restrictions.eq("id", 2));
	List list = criteria.list();

The eq() method of restriction class compares the result with id and returns.

Read More about the restriction on Criteria.

A Simple class of criteria join is given below

SelectCriteria.java

package net.roseindia.main;

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

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

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class SelectCriteria {

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

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

		Object object;

		try {
			// Creating a Criteria instance

			Criteria criteria = session.createCriteria(Contact.class);
			criteria.setFetchMode("Student", FetchMode.JOIN).add(
					Restrictions.eq("id", 1));
			List list = criteria.list();

			Iterator itr = list.iterator();
			System.out.println("\n");
			System.out.println("Student Details :- \n");
			if (list.size() == 0) {
				System.out.println("No Result Found !");
			}
			while (itr.hasNext()) {
				object = (Object) itr.next();
				System.out.printf("\t");
				System.out.println("First Name : "
						+ ((Contact) object).getFirstName());
			}

		} catch (HibernateException e) {

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

	}

}

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

select this_.ID as ID1_0_, this_.first_name as first2_1_0_, this_.last_name as last3_1_0_ from contact this_ where this_.ID=?

Student Details :-

First Name : John MacSmith

Download Complete Source Code

Related Tags for Hibernate Criteria Join:

Advertisements

Ads

Ads

 
Advertisement null

Ads