Home Tutorial Hibernate Hibernate Criteria restrictions Query Example

 
 

Share on Google+Share on Google+
Hibernate Criteria restrictions Query Example
Posted on: March 28, 2011 at 12:00 AM
Advertisement
In this Example, We will discuss about hibernate criteria query, The interface org.hibernate.Criteria is used to create the criterion for the search.

Hibernate Criteria restrictions Query Example

In this Example, We will discuss about hibernate criteria query, The interface org.hibernate.Criteria is used to create the criterion for the search. In this example we create a criteria instance and implement the restrictions class method. These methods are used to set a restriction on the results to be retrieved.

Here is the simple Example code files.

Criteria_Example_Add_Restriction.java

package roseindia;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import roseindia.bean.User;
import roseindia.util.HibernateUtil;

public class Criteria_Restriction {

	public static void main(String[] args) {

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

		User user = null;

		try {
			// Creating a Criteria instance
			Criteria crit = session.createCriteria(User.class);
			crit.setMaxResults(10);
			List users = crit.list();

			users = session.createCriteria(User.class).add(
					Restrictions.like("empName", "gyan%"))
					.add(
					Restrictions.or(Restrictions.eq("expInMonth",
					new Integer(0)), Restrictions
					.isNull("expInMonth"))).list();
			System.out.println("Size= " + users.size());
			System.out.println(users);

			// Example-2
			users = session.createCriteria(User.class).add(
				Restrictions.in("empName", new String[] { "gyan 0",
							"gyan 1", "gyan 2" })).add(
				Restrictions.disjunction().add(
				Restrictions.isNull("expInMonth")).add(
				Restrictions.eq("expInMonth", new Integer(0))))
					.list();

			System.out.println("Size= " + users.size());
			System.out.println(users);

		} catch (HibernateException e) {

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

	}

}

The bean class is as follows.

package roseindia.bean;

import java.util.Date;

public class User implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	private long empId = 0;
	private String empName = null;
	private String empAddr = null;
	private String empPhone = null;
	private String empEmail = null;
	private Date empDOB = null;
	private int expInMonth = 0;
	private double empSalary = 0.0;

	public User() {
	}

	public User(String empName, String empAddr, String empPhone,
			String empEmail, Date empDOB, int expInMonth, double empSalary) {
		this.empName = empName;
		this.empAddr = empAddr;
		this.empPhone = empPhone;
		this.empEmail = empEmail;
		this.empDOB = empDOB;
		this.expInMonth = expInMonth;
		this.empSalary = empSalary;
	}

	public long getEmpId() {
		return empId;
	}

	public void setEmpId(long empId) {
		this.empId = empId;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getEmpAddr() {
		return empAddr;
	}

	public void setEmpAddr(String empAddr) {
		this.empAddr = empAddr;
	}

	public String getEmpPhone() {
		return empPhone;
	}

	public void setEmpPhone(String empPhone) {
		this.empPhone = empPhone;
	}

	public String getEmpEmail() {
		return empEmail;
	}

	public void setEmpEmail(String empEmail) {
		this.empEmail = empEmail;
	}

	public Date getEmpDOB() {
		return empDOB;
	}

	public void setEmpDOB(Date empDOB) {
		this.empDOB = empDOB;
	}

	public int getExpInMonth() {
		return expInMonth;
	}

	public void setExpInMonth(int expInMonth) {
		this.expInMonth = expInMonth;
	}

	public double getEmpSalary() {
		return empSalary;
	}

	public void setEmpSalary(double empSalary) {
		this.empSalary = empSalary;
	}

	@Override
	public String toString() {
		return "User [empAddr=" + empAddr + ", empDOB=" + empDOB
			+ ", empEmail=" + empEmail + ", empId=" + empId + ", empName="
			+ empName + ", empPhone=" + empPhone + ", empSalary="
			+ empSalary + ", expInMonth=" + expInMonth + "]";
	}

}

We use the following code to insert the values in the database table using mapping file.

DataInsert.java

package roseindia;

import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import roseindia.bean.User;
import roseindia.util.HibernateUtil;

public class DataInsert {

	public static void main(String[] args) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		User user = null;

		try {
			transaction = session.beginTransaction();
			for (int i = 0; i < 10; i++) {
				user = new User("Gyan " + i, "NEW DELHI" + i,
				"68784654654" + i, "gyan@gmail.com" + i, new Date(),
					12 * i, 15398.00 * i);
				session.save(user);
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

}

The database table mapping is in the file User.hbm.xml and hibernate configuration file is hibernate.cfg.xml.

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/test</property>

<property name="connection.username">root</property>

<property name="connection.password"></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="roseindia/bean/User.hbm.xml" />

</session-factory>

</hibernate-configuration>

The User.hbm.xml file is as follows-

<?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="roseindia.bean.User" table="EMPLOYEE">

<id name="empId" type="long" column="EMP_ID">

<generator class="native" />

</id>

<property name="empName" type="java.lang.String" length="100"

not-null="false" column="EMP_NAME" />

<property name="empAddr" type="java.lang.String" length="100"

not-null="false" column="EMP_ADDR" />

<property name="empPhone" type="java.lang.String" length="100"

not-null="false" column="EMP_PHONE" />

<property name="empEmail" type="java.lang.String" length="100"

not-null="false" column="EMP_EMAIL" />

<property name="empDOB" type="java.util.Date" not-null="false"

column="EMP_DOB" />

<property name="expInMonth" type="int" not-null="false"

column="EXP_IN_MONTH" />

<property name="empSalary" type="double" not-null="false"

column="EMP_SALARY" />

</class>

</hibernate-mapping>

 

The HibernateUtil.java is as follows, is used to get the SessionFactory object to open session.

package 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;
	}
}

This example give the output the values from the table according to the criteria defined.

The structure of the database table is as follows:

The resultent query generated by hibernate is as follows which produces the output as follows

Hibernate: select this_.EMP_ID as EMP1_0_0_, this_.EMP_NAME as EMP2_0_0_, 
this_.EMP_ADDR as EMP3_0_0_, this_.EMP_PHONE as EMP4_0_0_, 
this_.EMP_EMAIL as EMP5_0_0_, this_.EMP_DOB as EMP6_0_0_, 
this_.EXP_IN_MONTH as EXP7_0_0_, this_.EMP_SALARY as EMP8_0_0_ from 
EMPLOYEE this_ where this_.EMP_NAME like ? and (this_.EXP_IN_MONTH=? or 
this_.EXP_IN_MONTH is null)

Size= 1
[User [empAddr=NEW DELHI0, empDOB=2011-03-28 15:19:28.0, 
empEmail=gyan@gmail.com0, empId=11, empName=Gyan 0, empPhone=687846546540,
 empSalary=0.0, expInMonth=0]]

Hibernate: select this_.EMP_ID as EMP1_0_0_, this_.EMP_NAME as EMP2_0_0_,
 this_.EMP_ADDR as EMP3_0_0_, this_.EMP_PHONE as EMP4_0_0_, 
this_.EMP_EMAIL as EMP5_0_0_, this_.EMP_DOB as EMP6_0_0_, 
this_.EXP_IN_MONTH as EXP7_0_0_, this_.EMP_SALARY as EMP8_0_0_ from 
EMPLOYEE this_ where this_.EMP_NAME in (?, ?, ?) and (this_.EXP_IN_MONTH is null 
or this_.EXP_IN_MONTH=?)

Size= 1
[User [empAddr=NEW DELHI0, empDOB=2011-03-28 15:19:28.0, empEmail=gyan@gmail.com0, 
empId=11, empName=Gyan 0, empPhone=687846546540, empSalary=0.0, expInMonth=0]]

Download the Code:

Advertisement

Related Tags for Hibernate Criteria restrictions Query Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 28, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com