Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

datetime - How do I query "older than three minutes" in JPA?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...