Reputation: 1590
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));
Upvotes: 0
Views: 4660
Reputation: 131
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()));
Upvotes: 5