Saturday, November 13, 2010

Hibernate Criteria Query Between Date

Mysql- using Date function.

introduction:
                     we have to handle Date in our program. So we need to include Date function into our table student.

Step 1:
            Create Database I have created database as Navalady.

Note: No need to create Database. Because we have already created Database named as Navalady)       


Step 2:
            Already we have created table name as student. So also no need to create table.

Step 3:
We have to use the date in our program. So we include joining date of student into our table.

How to add new field into our existing table?

Mysql > alter table table_name ADD(field_name field_type);

Mysql > alter table student ADD(joindate Date);

Step 4:
                Insert new records into student table.


















Step 5:

Insert joining date into already include student.
Successfully we have included the join date to student.

Hibernate Criteria Query-BetweenDate


AIM:
                        From this post we will learn how to use betweenDate to get result.

Problem:
                        To get student who get admission between two dates.


Solution:

Made some changes in student table.

Step 1:
            Create Hibernate Reverse Engineering wizard

Step 2:
            Create HibernateUtil.java

Step 3:
            Create POJO class and mapping files



Step 4:

            Create jsp file named as BetweenDate.jsp

Include following coding into the BetweenDate.jsp

< %@page import="java.util.*"% >
< %@page import="org.hibernate.*" % >
< %@page import="org.hibernate.cfg.Configuration" % >
< %@page import="org.hibernate.cfg.*" % >
< %@page import="org.hibernate.criterion.*" % >
< %@page import="Hiber.Student" % >

< html >
< head >
< title > Criteria Example between Date < /title >
< /head >
< body >
< %
try
{
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session s=sessionFactory.openSession();

Criteria crit=s.createCriteria(Student.class);

Date startDate=new Date("1999/06/22");
Date endDate=new Date("1999/06/26");

crit.add(Expression.between("joindate", startDate,endDate));

crit.setMaxResults(4);
List list=crit.list();
Iterator iterator=list.iterator();
while(iterator.hasNext())
{
Student ss=(Student)iterator.next();
out.println(ss.getStuname());
}

}
catch(Exception e)
{
out.println(e);
}
% >
< /body >
< /html >


Output:

To check manually using mysql query.
mysql > select stuname from student where joindate between ('1999/06/22') and (‘1999/06/26’);




No comments:

Post a Comment