Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

Hibernate Built-in criterion "between" Date

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

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

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

Ads
Share on Google+Share on Google+

Hibernate Built-in criterion "between" Date

Posted on: March 26, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Hibernate Built-in criterion "between" Date  

Post your Comment


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

Ads

 

Ads