日期的hibernate标准

在oracle我有格式的日期

2011年4月17日19:20:23.707000000

我想检索17-04-2011的所有订单。

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY"); String myDate = "17-04-2011"; Date date = formatter.parse(myDate); Criteria criteria = session.createCriteria(Order.class); Criterion restrictDate = Restrictions.like("orderDate",date); 

但它给我带来空洞的结果:

为什么使用Restrictions.like(... )?

您应该使用Restrictions.eq(...)

请注意,您还可以将日期对象上的.gt.lt.gt.gt用作比较运算符。 LIKE运算符不适用于这种情况,因为当您希望根据列的部分内容匹配结果时, LIKE非常有用。 请参阅http://www.sql-tutorial.net/SQL-LIKE.asp以获取参考。

例如,如果您的名称列中包含某些人的全名,则可以执行where name like 'robert %'名称,以便返回名称以'robert '开头的所有条目( %可以替换任何字符)。

在您的情况下,您知道您尝试匹配的日期的完整内容,因此您不应该使用LIKE而是相等。 我想Hibernate在这种情况下不会给你任何exception,但无论如何你可能会遇到与Restrictions.eq(...)相同的问题。

您使用代码获得的日期对象:

 SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY"); String myDate = "17-04-2011"; Date date = formatter.parse(myDate); 

此日期对象等于17-04-2011在0h,0分钟,0秒和0纳秒。

这意味着您在数据库中的条目必须具有该日期。 我的意思是,如果您的数据库条目的日期为“2011年4月17日19:20:23.707000000”,那么它将无法检索,因为您只是要求该日期:“2011年4月17日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) ); 

通过使用这种方式,您可以获得所选记录的列表。

 GregorianCalendar gregorianCalendar = new GregorianCalendar(); Criteria cri = session.createCriteria(ProjectActivities.class); cri.add(Restrictions.ge("EffectiveFrom", gregorianCalendar.getTime())); List list = cri.list(); 

所有记录将生成到大于或等于’08 -Oct-2012’的列表中,或者在标准的限制条件( gregorianCalendar.getTime() )的第二参数处传递用户接受日期以获取记录。

如果列是时间戳,您可以执行以下操作:

  if(fromDate!=null){ criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')")); } if(toDate!=null){ criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')")); } resultDB = criteria.list();