Compare current Date time in JPA query

て烟熏妆下的殇ゞ 提交于 2021-02-04 22:13:07

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/11686264/compare-current-date-time-in-jpa-query

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