为什么使用
Restrictions.like(...)?
您应该使用
Restrictions.eq(...)。
请注意,您也可以使用
.le,
.lt,
.ge,
.gt在日期对象作为比较操作。
LIKE运算符不适用于这种情况,因为
LIKE当您要根据列的部分内容匹配结果时很有用。请参阅http://www.sql-
tutorial.net/SQL-LIKE.asp作为参考。
例如,如果您的姓名列中包含某些人的全名,则可以这样做,
where name like 'robert %'以便您返回名称以
'robert'(
%可以替换任何字符)开头的所有条目。
在您的情况下,您知道要匹配的日期的全部内容,因此您不应该使用
LIKE相等。我猜Hibernate在这种情况下不会给您任何异常,但是无论如何,您可能会遇到同样的问题
Restrictions.eq(...)。
您的日期对象带有以下代码:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");String myDate = "17-04-2011";Date date = formatter.parse(myDate);此日期对象等于07:00、0分,0秒和0纳秒的17-04-2011。
这意味着您在数据库中的条目必须具有 确切的 日期。我的意思是,如果您的数据库条目的日期为“ 17-April-2011
19:20:23.707000000”,那么它将不会被检索,因为您只要求输入该日期:“ 17-April-2011 00:00:
00.0000000000”。
如果要检索给定日期的数据库的所有条目,则必须使用以下代码:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY"); String myDate = "17-04-2011"; // Create date 17-04-2011 - 00h00 Date minDate = formatter.parse(myDate); // Create date 18-04-2011 - 00h00 // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1)); Conjunction and = Restrictions.conjunction(); // The order date must be >= 17-04-2011 - 00h00 and.add( Restrictions.ge("orderDate", minDate) ); // And the order date must be < 18-04-2011 - 00h00 and.add( Restrictions.lt("orderDate", maxDate) );


