Java 使用 JPA 比较两个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1347823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare two dates with JPA
提问by Kiva
I need to compare two dates in a JPQL query but it doesn't work.
我需要在 JPQL 查询中比较两个日期,但它不起作用。
Here is my query:
这是我的查询:
Query query = em.createQuery(
"SELECT h
FROM PositionHistoric h,
SeoDate d
WHERE h.primaryKey.siteDb = :site
AND h.primaryKey.engineDb = :engine
AND h.primaryKey.keywordDb = :keyword
AND h.date = d
AND d.date <= :date
ORDER BY h.date DESC");`
My parameter date is a java.util.Date
我的参数日期是一个 java.util.Date
My query return a objects list but the dates are upper and lower to my parameter.
我的查询返回一个对象列表,但日期高于和低于我的参数。
Someone kown how to do this ?
有人知道怎么做吗?
Thanks.
谢谢。
回答by Nettogrof
I suggest to use java.sql.Date instead of java.util.Date
我建议使用 java.sql.Date 而不是 java.util.Date
Because you pass it to a JPQL(kind of SQL).
因为您将它传递给 JPQL(一种 SQL)。
I usually use TIMESTAMP instead of Date, but if you didn't have the choice..
我通常使用 TIMESTAMP 而不是 Date,但如果你没有选择的话..
And is it : h.date = d.date instead h.date = d ?
是不是: h.date = d.date 而不是 h.date = d ?
回答by ChssPly76
The query you should use is:
您应该使用的查询是:
FROM PositionHistoric h
INNER JOIN FETCH h.date
WHERE h.primaryKey.siteDb = :site
AND h.primaryKey.engineDb = :engine
AND h.primaryKey.keywordDb = :keyword
AND h.date.date <= :date
Note that ordering by h.date
is rather pointless (as it points to SeoDate entity and thus in effect you're ordering by PK) and you can't order by h.date.date
since SeoDate is mapped as many-to-one
.
请注意,排序依据h.date
是毫无意义的(因为它指向 SeoDate 实体,因此实际上您是按 PK 排序的)并且您无法排序,h.date.date
因为 SeoDate 被映射为many-to-one
.
Also note that INNER JOIN FETCH h.date
line is not necessary per se but it will save you some overhead on additional lazy queries IF you will actually need to use SeoDate attributes in the returned list.
另请注意,INNER JOIN FETCH h.date
line 本身不是必需的,但如果您实际上需要在返回的列表中使用 SeoDate 属性,它会为您节省一些额外的延迟查询的开销。