是否可以在JPA @Query语句中具有条件来确定时间戳是否匹配当前日期?

发布于 01-20 15:27 字数 419 浏览 3 评论 0原文

我有一个现有的JPA @Query,我需要在其中仅在当前日期匹配时间戳列的位置返回行中添加加法条件。基本上想知道是否有可能的事情是可能的:

@Query("SELECT .. " +
        "WHERE .. " +
                "AND isCurrentDay(c.completedTs))"

否则可以通过本机查询来完成我需要的东西。

编辑:我的解决方案最终是使用本机查询,例如:

@Query(value = "SELECT ... " + 
"WHERE ... " + 
     "AND CONVERT (date, c.completedTs) = CONVERT (date, GETDATE()))", 
nativeQuery = true)

I have an existing JPA @Query that I need to add an addition condition to the WHERE such that it'll only return rows where the current date matches that of a timestamp column. Basically wondering if something along the lines of this is possible:

@Query("SELECT .. " +
        "WHERE .. " +
                "AND isCurrentDay(c.completedTs))"

Otherwise can accomplish what I need with a native query.

Edit: My solution ended up being to use a Native Query like:

@Query(value = "SELECT ... " + 
"WHERE ... " + 
     "AND CONVERT (date, c.completedTs) = CONVERT (date, GETDATE()))", 
nativeQuery = true)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

祁梦 2025-01-27 15:27:50

我将使用本机查询使用curdate SQL语言说明您正在写的语言会更安全。例如,对于MySQL + JPA,它看起来像这样:

@Query("SELECT .. " +
        "WHERE .. " +
                "AND WHERE DATE(`completed_ts`)=CURDATE()", 
       nativeQuery = true)

I'll be it would be safer to do it through native queries using the CURDATE sql statement of the language you are writing in. For example, for MySQL + JPA it would look something like this:

@Query("SELECT .. " +
        "WHERE .. " +
                "AND WHERE DATE(`completed_ts`)=CURDATE()", 
       nativeQuery = true)
向地狱狂奔 2025-01-27 15:27:50

JPQL暴露了很少的功能以关联当前日期/时间:

从文档中:

current_date:此功能返回数据库服务器上当前日期的值。
Current_Time:此功能返回数据库服务器上当前时间的值。
Current_timestamp:此功能返回数据库服务器上当前时间戳的值。

参考: javadoc

可以通过以下方式使用这些直接访问当前日期,

@Query("SELECT .. " +
        "WHERE .. " +
                "AND c.completedTs=CURRENT_DATE )"

请注意,afaik,这些是香草函数,不支持表达式,即,您不能执行Current_Date-1。

JPQL Exposes few functions to associate CURRENT date/time :

From the docs :

CURRENT_DATE: This function returns the value of current date on the database server.
CURRENT_TIME: This function returns the value of current time on the database server.
CURRENT_TIMESTAMP: This function returns the value of current timestamp on the database server.

ref : javadoc

These can be used in the following way to directly access current date

@Query("SELECT .. " +
        "WHERE .. " +
                "AND c.completedTs=CURRENT_DATE )"

Please note , AFAIK , these are vanilla functions and do not support expressions , i.e , you cannot do CURRENT_DATE-1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文