Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate4 Hibernate Built-in criterion "between" Date

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate Built-in criterion "between" Date

Advertisement
In this tutorial you will learn about how to use the built-in criterion ' between ' with the Date.

Hibernate Built-in criterion "between" Date

In this tutorial you will learn about how to use the built-in criterion ' between ' with the Date.

Hibernate provides the facility to make a Criteria query restricted. An interface Criterion is responsible for representing a query criterion as an object oriented this query might be used in a Criteria query to make it restricted. However, this interface may be implemented in the class where a custom restriction criteria is to be defined. A class Restrictions is a factory class that provides the built-in criterion.

Example :

Here I am going to give an example of built-in criterion "between" which is provided by the Restrictions factory class. Between criterion applied the between constraint on the specified properties i.e it returns the value between the specified minimum and maximum range. In this example I will fetch the id, name, gender of Employee2 from the table employeename2 between the specified date.

Table employeename2

CREATE TABLE `employeename2` ( 
`id` int(10) NOT NULL, 
`name` varchar(15) default NULL, 
`gender` varchar(5) default NULL, 
`age` int(10) default '0', 
`dateOfBirth` date default NULL, 
PRIMARY KEY (`id`) 
)

Employee2.java

package roseindia;

import java.util.Date;
public class Employee2 {
private int id; 
private String name;
private String gender;
private int age;
private Date dateOfBirth;

public Employee2()
{

}
public Employee2(String name, String gender, int age, Date dateOfBirth)
{
this.name = name;
this.gender = gender;
this.age = age;
this.dateOfBirth = dateOfBirth;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getGender()
{
return gender;
}
public void setGender(String gender)
{
this.gender = gender;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public Date getDateOfBirth()
{
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth)
{
this.dateOfBirth = dateOfBirth;
}
}

Employee2.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name= "roseindia.Employee2" table="employeename2">
<id name= "id" type="int" >
<generator class="native" />
</id>
<property name="name" />
<property name="gender" />
<property name="age" type="int" />
<property name="dateOfBirth" type="java.util.Date" />
</class>

</hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/data
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>

</hibernate-configuration>

HibernateBetweenDateExample.java

package roseindia;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Iterator;
import java.util.Date;
import org.hibernate.SessionFactory;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Criteria;

public class HibernateBetweenDateExample {
private static SessionFactory sessionFactory=null;
private static ServiceRegistry serviceRegistry=null;
public static void main(String args[])
{
Session session = null;

try
{
Configuration cfg = new Configuration().addResource("roseindia/Employee2.hbm.xml");
cfg.configure();

serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch(Throwable th)
{
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
}
try
{
session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(Employee2.class);
DateFormat format = 
new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
Date startDate = 
(Date)format.parse("23-03-1984 00:00:00");
Date endDate = 
(Date)format.parse("01-04-1986 00:00:00"); 

List ls = criteria.add(Restrictions.between("dateOfBirth", new Date(startDate.getTime()), new Date(endDate.getTime()))).list();
Iterator it = ls.iterator();
System.out.println("Id \t Name \tGender \tAge \tDateOfBirth");
while(it.hasNext())
{
Employee2 emp2 = (Employee2)it.next();
System.out.println(emp2.getId()+"\t"+emp2.getName()+"\t"+emp2.getGender()+"\t"+emp2.getAge()+"\t"+emp2.getDateOfBirth());
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
session.close();
}
}

}

Output :

table employeename2

When you will execute the java file HibernateBetweenDateExample.java ( RightClick -> Run As -> Java Application ) a query and output will be displayed on your console as :

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 23, 2012 6:52:23 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.gender as gender0_0_, this_.age as age0_0_, this_.dateOfBirth as dateOfBi5_0_0_ from employeename2 this_ where this_.dateOfBirth between ? and ?

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


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 26, 2012

Related Tutorials

Discuss: Hibernate Built-in criterion "between" Date  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com