2014-09-05 73 views
10

我必须比较hibernate hql查询中的两个日期。 我在我的java bean中使用java.util.Date,并在mysql数据库中使用timestamp作为数据类型。在没有时间戳的HQL中比较日期

select t from Task t where t.modifiedDate > t.endDate; 

上面的查询比较时间和日期。我应该如何在没有时间的情况下比较上述查询中的日期。

回答

13

参考Hibernate单证可用日期函数

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html

在14.10节通知此行

second(...), minute(...), hour(...), day(...), month(...), and year(...) 

所以这应该工作

... where year(t.endDate) > year(t.startDate) 
    and month(t.endDate) > month(t.startDate) 
    and day(t.endDate) > day(t.startDate) 

解决方案报告为满意问题是

... where DATE(t.endDate) > (t.startDate) 
+0

这是给我用一个月和一年分别比较......但我有比较充分** **日期在像时间* * 06-09-2014 ** – 2014-09-06 05:57:18

+2

它适用于以下更改**其中DATE(t.endDate)>(t.startDate)** – 2014-09-19 14:19:16

+0

很高兴为您效劳。我正在用您的解决方案编辑答案,而不是将解决方案留在评论中。这是Stackoverflow做事的方式。 – carbontax 2014-09-19 22:14:54

0

提出的解决方案与date()功能似乎并不纯SQL和(使用SQL Server)对我不起作用。最初的解决方案(单独比较日,月和年)是朝着正确方向迈出的一步,但不能以这种方式完成,例如,对于未来的日期,如果一个月的日期不需要更长越大,等下面的SQL,但是,应该工作:

(year(t.endDate) > year(t.startDate)) 
or 
(year(t.endDate) = year(t.startDate) 
    and 
    month(t.endDate) > month(t.startDate)) 
or 
(year(t.endDate) = year(t.startDate) 
    and 
    month(t.endDate) = month(t.startDate) 
    and 
    day(t.endDate) > day(t.startDate))