How do I query “older than three minutes” in JPA?

家住魔仙堡 提交于 2019-12-17 19:14:51

问题


Is there a way to put a date range condition referencing the current time in a JPA query (that is compatible across databases)?

I can do

SELECT m FROM Mail m WHERE m.sentAt < :date

but I want to do it without having to bind a parameter (so that this can be configured as part of the named query repository and the date calculation logic does not have to enter the calling code).

So instead of :date I need "currentTime minus 3 minutes" as a hard-code literal.


回答1:


JPA supports the CURRENT_TIMESTAMP and CURRENT_TIME functions.

https://en.wikibooks.org/wiki/Java_Persistence/JPQL#Functions

The JPA spec does not have date functions, but some JPA providers such as EclipseLink do.

http://java-persistence-performance.blogspot.com/2012/05/jpql-vs-sql-have-both-with-eclipselink.html

JPA 2.1 also defines the FUNCTION operator to call database functions.

In EclipseLink I would try,

SELECT m FROM Mail m WHERE m.sentAt < SQL("(sysdate - interval '3' minute)")

or,

SELECT m FROM Mail m WHERE m.sentAt < SQL("(? - interval '3' minute)", CURRENT_TIMESTAMP)



回答2:


If you are using Hibernate JPA implementation and an Oracle dialect, then you can use SYSDATE function which returns current date and time. If you add 1 to SYSDATE it will add one day.

Adding fractions is also supported:

  • sysdate + 1/24 will add an hour
  • sysdate + 1/(24*60) will add a minute
  • sysdate + 1/(24*60*60) will add a second

So instead of :date I need "currentTime minus 3 minutes" as a hard-code literal.

sysdate - 3/(24*60) will subtract 3 minutes from current date and time:

SELECT m FROM Mail m WHERE m.sentAt < sysdate - 3/(24*60)

Records older than 3 minutes will be returned and no parameter binding is needed.



来源:https://stackoverflow.com/questions/18505064/how-do-i-query-older-than-three-minutes-in-jpa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!