Postgres Interval无法使用本机spring数据JPA查询 [英] Postgres Interval not working with native spring data JPA query

查看:140
本文介绍了Postgres Interval无法使用本机spring数据JPA查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带间隔的本机查询。当我在查询中硬编码 day 时,查询工作正常:

I have created a native query with interval. The query works fine when i hard code day in query:

@Query(value="select * from orders where created_date  < clock_timestamp() - interval ' 5 days'",nativeQuery=true)

但是当我使用 @Param 提供数据时,

But when i provide data with @Param like this:

@Query(value="select * from orders where created_date  < clock_timestamp() - interval :day 'days'",nativeQuery=true)
List<Order> getData(@Param("day") String day)

我收到此错误:


原因:org.postgresql.util.PSQLException:错误:
或 $ 1附近的语法错误

Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"


推荐答案

您不能为这样的间隔提供值。您需要使用间隔基本单位乘以参数值:

You can't provide a value for an interval like that. You need to multiple the parameter value with your interval base unit:

"select * from orders 
where created_date  < clock_timestamp() - (interval '1' day) * :days"

,您可以简化为:

"select * from orders 
where created_date  < clock_timestamp() - :days"

另一个选择是 make_interval() 函数。您可以为不同的单位传递多个参数。

Another option is the make_interval() function. You can pass multiple parameters for different units.

"select * from orders 
where created_date  < clock_timestamp() - make_interval(days => :days)"

表示法 days => ... 是函数调用的命名参数。如果变量表示小时,则可以使用 make_interval(hours => ..)

The notation days => ... is a named parameter for a function call. If the variable represents hours, you could use make_interval(hours => ..)

这篇关于Postgres Interval无法使用本机spring数据JPA查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆