Postgres Interval无法使用本机spring数据JPA查询

Aji*_*man 2 java postgresql spring-data-jpa

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

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

但是当我提供这样的数据时@Param

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

我收到此错误:

由以下原因引起:org.postgresql.util.PSQLException:错误:“ $ 1”或附近的语法错误

小智 6

此条目中提供了一种解决方案Spring Boot Query annotation with nativeQuery 在 Postgresql 中不起作用

基本上:

@Query(value="select * from orders where created_date  < clock_timestamp() - ( :toTime )\\:\\:interval",nativeQuery=true)
Run Code Online (Sandbox Code Playgroud)

'toTime' 是您存储库中的参数,可以是天、小时、分钟...等(Postgres 中的审查间隔文档)@Param("toTime") String toTime


a_h*_*ame 5

您无法为这样的间隔提供值。您需要将参数值与间隔基本单位乘以:

"select * from orders 
where created_date  < clock_timestamp() - (interval '1' day) * :days"
Run Code Online (Sandbox Code Playgroud)

在处理几天时,可以将其简化为:

"select * from orders 
where created_date  < clock_timestamp() - :days"
Run Code Online (Sandbox Code Playgroud)

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

"select * from orders 
where created_date  < clock_timestamp() - make_interval(days => :days)"
Run Code Online (Sandbox Code Playgroud)

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