Home Hibernate Examples Criteria hibernate criteria date between

Ask Questions?

View Latest Questions


 
 

hibernate criteria date between
Posted on: April 7, 2011 at 12:00 AM
Advertisement
In this Tutorial, We will discuss about hibernate criteria query, The interface org.hibernate.criterion.Restrictions  is used to create the criterion for the search.

hibernate criteria Date Between Example

In this Tutorial, We will discuss about hibernate criteria query, The interface org.hibernate.criterion.Restrictions  is used to create the criterion for the search. In this example we create a criteria instance and implement the factory methods for obtaining certain built-in Criterion types method. In This example search the result according to like and between condition according to the given dates.

Here is the simple Example code files.

CriteriaDateBetween.java

package roseindia;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import roseindia.bean.User;
import roseindia.util.HibernateUtil;

public class CriteriaDateBetween {

	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);
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date d1 = (Date) format.parse("2011-04-11 15:21:26");
			Date d2 = (Date) format.parse("2011-04-16 15:21:26");
			crit.setMaxResults(10);
			crit.add(Restrictions.like("UserName", "User%"));
			crit.add(Restrictions.between("UserDOB", d1, d2));
			List list = crit.list();
			Iterator itr = list.iterator();
			while (itr.hasNext()) {
			user = (User) itr.next();
			System.out.println("UserId: " + user.getUserId());
			System.out.printf("\t");
			System.out.println("UserName: " + user.getUserName());
			System.out.printf("\t");
			System.out.println("UserAddr: " + user.getUserAddr());
			System.out.printf("\t");
			System.out.println("ExpInMonth: " + user.getExpInMonth());

			}

		} catch (Exception 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 Id = 0;
	private int UserId = 0;
	private String UserName = null;
	private String UserAddr = null;
	private String UserPhone = null;
	private String UserEmail = null;
	private Date UserDOB = null;
	private int expInMonth = 0;
	private double UserIncome = 0.0;

	public User() {
	}

	public User(int UserId, String UserName, String UserAddr, String UserPhone,
		String UserEmail, Date UserDOB, int expInMonth, double UserIncome) {
		this.UserId = UserId;
		this.UserName = UserName;
		this.UserAddr = UserAddr;
		this.UserPhone = UserPhone;
		this.UserEmail = UserEmail;
		this.UserDOB = UserDOB;
		this.expInMonth = expInMonth;
		this.UserIncome = UserIncome;
	}

	public long getId() {
		return Id;
	}

	public void setId(long id) {
		Id = id;
	}

	public int getUserId() {
		return UserId;
	}

	public void setUserId(int userId) {
		UserId = userId;
	}

	public String getUserName() {
		return UserName;
	}

	public void setUserName(String userName) {
		UserName = userName;
	}

	public String getUserAddr() {
		return UserAddr;
	}

	public void setUserAddr(String userAddr) {
		UserAddr = userAddr;
	}

	public String getUserPhone() {
		return UserPhone;
	}

	public void setUserPhone(String userPhone) {
		UserPhone = userPhone;
	}

	public String getUserEmail() {
		return UserEmail;
	}

	public void setUserEmail(String userEmail) {
		UserEmail = userEmail;
	}

	public Date getUserDOB() {
		return UserDOB;
	}

	public void setUserDOB(Date userDOB) {
		UserDOB = userDOB;
	}

	public int getExpInMonth() {
		return expInMonth;
	}

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

	public double getUserIncome() {
		return UserIncome;
	}

	public void setUserIncome(double userIncome) {
		UserIncome = userIncome;
	}

	@Override
	public String toString() {
		return "User [UserAddr=" + UserAddr + ", UserDOB=" + UserDOB
		+ ", UserEmail=" + UserEmail + ", UserId=" + UserId
		+ ", UserName=" + UserName + ", UserPhone=" + UserPhone
		+ ", UserSalary=" + UserIncome + ", 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(1 * i, "User " + i, "NEW DELHI" + i,
				"999999458" + i, "User@gmail.com" + i, new Date(),
						12 * i, 25000.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="UserData">
<id name="Id" type="long" column="ID">
<generator class="native" />
</id>
<property name="UserId" type="int" length="100" not-null="false"
column="USER_ID" />
<property name="UserName" type="java.lang.String" length="100"
not-null="false" column="USER_NAME" />
<property name="UserAddr" type="java.lang.String" length="100"
not-null="false" column="USER_ADDR" />
<property name="UserPhone" type="java.lang.String" length="100"
not-null="false" column="USER_PHONE" />
<property name="UserEmail" type="java.lang.String" length="100"
not-null="false" column="USER_EMAIL" />
<property name="UserDOB" type="java.util.Date" not-null="false"
column="USER_DOB" />
<property name="expInMonth" type="int" not-null="false"
column="EXP_IN_MONTH" />
<property name="UserIncome" type="double" not-null="false"
column="USER_INCOME" />
</class>
</hibernate-mapping>

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

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 resultant query generated by hibernate is as follows which produces the output as follows

Hibernate: select this_.ID as ID0_0_, this_.USER_ID as USER2_0_0_, this_.USER_NAME 
as USER3_0_0_, this_.USER_ADDR as USER4_0_0_, this_.USER_PHONE as 
USER5_0_0_, this_.USER_EMAIL as USER6_0_0_, this_.USER_DOB as USER7_0_0_, 
this_.EXP_IN_MONTH as EXP8_0_0_, this_.USER_INCOME as USER9_0_0_ from 
UserData this_ where this_.USER_NAME like ? and this_.USER_DOB between ? and ? limit ?

Download Source Code

Related Tags for hibernate criteria date between:


DMCA.com