Beginner
Beginner

Reputation: 875

Compare current Date time in JPA query

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. ??

Upvotes: 11

Views: 46273

Answers (2)

youhans
youhans

Reputation: 6849

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

Upvotes: 7

JB Nizet
JB Nizet

Reputation: 691735

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);

Upvotes: 17

Related Questions