Hibernate Criteria
Posted on: April 4, 2011 at 12:00 AM
In this tutorial you will learn about the hibernate criteria

Hibernate Criteria

org.hibernate.Criteria is an interface which is very powerful alternatives of HQL (Hibernate Query Language) with some limitations. It is used where search on multi criteria required, becouse Hibernate Query Language is not so much effective there. It creates a query based on objects and allows to execute them. It represents a query against the persistence class.

In HQL you need to check and compare criteria that where it is first criteria to append the WHERE syntax. While in Criteria you don not need to compare the first criteria to include the WHERE sysntax.

Hibernate Criteria is very convenient way for search functionality, where a numbers of conditions can be placed upon the result set. It is very Simplified API for fetching data by criterion objects.

The Hibernate session is the factory of Criteria, It is obtained from the factory methods

Criteria criteria = session.createCriteria(User.class);
criteria.setMaxResults(3);
criteria.add(Restrictions.ne("empName", "John"));
List list = criteria.list();

An Example of select criteria is given below.


Bean Class

Student.java

package net.roseindia.bean;


public class Student implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	private int rollNo;
	private String name;
	private String course;
	private String address;
	
	public Student() {
		// TODO Auto-generated constructor stub
	}
	
	public Student(int roll, String name, String course, String address) {
		this.rollNo=roll;
		this.name=name;
		this.course=course;
		this.address=address;
	}
	
	public int getRollNo() {
		return rollNo;
	}
	public void setRollNo(int rollNo) {
		this.rollNo = rollNo;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCourse() {
		return course;
	}
	public void setCourse(String course) {
		this.course = course;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
}

hbm file of the bean class

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="net.roseindia.bean.Student" table="student">
<id name="rollNo" type="int" column="roll_no">
<generator class="native" />
</id>
<property name="name" type="java.lang.String" length="100"
not-null="false" column="name" />
<property name="course" type="java.lang.String" length="50"
not-null="false" column="course" />
<property name="address" type="java.lang.String" length="200"
not-null="false" column="address" />
</class>
</hibernate-mapping>


Util Class

HibernateUtil.java

package net.roseindia.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

SelectCriteria.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 SelectCriteria {

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

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

		Student student = null;

		try {
			// Creating a Criteria instance
			Criteria criteria = session.createCriteria(Student.class);
			criteria.add(Restrictions.eq("name", "John"));
			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()) {
				student = (Student) itr.next();
				System.out.printf("\t");
				System.out.println("Roll No: " + student.getRollNo());
				System.out.printf("\t");
				System.out.println("Name : " + student.getName());
				System.out.printf("\t");
				System.out.println("Course : " + student.getCourse());
				System.out.printf("\t");
				System.out.println("Address: " + student.getAddress());
				System.out.printf("\t");
			}

		} catch (HibernateException e) {

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

	}

}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernatetutorial</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="net/roseindia/bean/Student.hbm.xml" />

</session-factory>

</hibernate-configuration>



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


Student Details :-

Roll No: 1
Name : John
Course : MCA
Address: Delhi

Download Select Source Code

Related Tags for Hibernate Criteria:

Advertisements

Ads

 
Advertisement null

Ads