Home Hibernate Examples Criteria Hibernate Criteria Join

Ask Questions?

View Latest Questions


 
 

Hibernate Criteria Join
Posted on: October 7, 2013 at 12:00 AM
Advertisement
Here we have discussed Hibernate Criteria Join operation of Hibernate Criteria with a simple example.

Hibernate Criteria is an interface that is used for search functionality in Hibernate Query Language (HQL). It is a Simplified API that fetches data by criterion objects. There are many options available in hibernate to use criteria query, one of them is Hibernate Criteria Join which performs join operation.

For example, if we have to perform a operation like:

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

Then this statement can be written using Criteria:

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

Call the setFetchMode(ClassName, Type of operation). Then in the setFetchMode() method provide the name of the class and type of operation.

If you have to apply any restriction:

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

Then the code will change to:

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

eq() method of Restrictions class compares the result with id and returns the value.

Example of Hibernate Criteria join:

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();
}

}

}

Output:

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

Resources:

Related Tags for Hibernate Criteria Join:


DMCA.com