Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare current Date time in JPA query

Tags:

java

jpa

I want to compare the date in database with current dateTime in JPA query :

captureLimitDate < currentDateTime

my requirement is as follows :

database.captureLimitDate : 04/07/2012 19:03:00 currentDateTime : 04/07/2012 20:03:00

My JPAQuery is this :

SELECT o FROM Operation o"
+ " WHERE ( o.merchantId =:merchantId ) AND "
+ "(o.captureLimitDate < currentDateTime ) ";

And Operation class has captureLimitDate as java.util.Date

    @Generated(value = "XA", comments = "0,_8BedAMXZEeGHf_Dj4YaPyg")
     private Date captureLimitDate;

I want to compare both current date and time . will the above query works. ??

like image 651
Beginner Avatar asked Jul 27 '12 10:07

Beginner


2 Answers

CURRENT_TIMESTAMP must be used to refere to the current date and time in a JPQL query:

select o from Operation o
where o.merchantId = :merchantId
and o.captureLimitDate < CURRENT_TIMESTAMP

If the current date and time is in fact a date coming from user input (and which is thus not the current date and time, then you do it like you do for the merchantId:

select o from Operation o
where o.merchantId = :merchantId
and o.captureLimitDate < :maxDateTime

And you set the parameter using

query.setParameter("maxDateTime", maxDateTime, TemporalType.TIMESTAMP);
like image 64
JB Nizet Avatar answered Oct 26 '22 09:10

JB Nizet


JPA defines special JPQL expressions that are evaluated to the date and time on the database server when the query is executed:

CURRENT_DATE - is evaluated to the current date (a java.sql.Date instance).

CURRENT_TIME - is evaluated to the current time (a java.sql.Time instance).

CURRENT_TIMESTAMP - is evaluated to the current timestamp, i.e. date and time (a java.sql.Timestamp instance).

More info: Click here

like image 33
youhans Avatar answered Oct 26 '22 09:10

youhans