简体   繁体   中英

Date comparison using Hibernate Criteria API

Environment : Hibernate 4 Tomcat 6

Issue :

I have a column in MySQL database with DATETIME type (abhishekDate is the column name).
I want to compare the user supplied date with this DATETIME column.

But the comparison should NOT INCLUDE the time part of the DATETIME column. The comparison should be based on DATE part only.

Since the query is dynamic , I am using Criteria API. But I am not able to achieve the same using Criteria API. I have tried below code but its not working.

Can you please help on how to write this query ?

Am I using correct approach for the same ?

The exception I am getting is :

Mar 08, 2016 9:26:59 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet mvc-dispatcher threw exception
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'abhishekDate' in 'where clause'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)

But abhishekDate is present in User class (or table)

Code :

Criteria criteria = getSession().createCriteria(User.class);
Conjunction and = Restrictions.conjunction();

and.add(Restrictions.sqlRestriction("year(abhishekDate) = ? ",abhishekDate,org.hibernate.type.StandardBasicTypes.DATE));
and.add(Restrictions.sqlRestriction("month(abhishekDate) = ? ",abhishekDate,org.hibernate.type.StandardBasicTypes.DATE));
and.add(Restrictions.sqlRestriction("day(abhishekDate) = ? ",abhishekDate,org.hibernate.type.StandardBasicTypes.DATE));

I tried another way and it is working for me . I check the date in my table is between the user date and user date plus one day as follow.

Calendar cal = Calendar.getInstance();
cal.setTime(userDate);
cr.add(Restrictions.ge("yourDate", cal.getTime()));
cal.add(Calendar.DATE, 1);
cr.add(Restrictions.le("yourDate", cal.getTime()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM