Postgres Interval Spring Data Dynamic Parameter not working

我们两清 提交于 2019-12-24 07:53:06

问题


I need to pass in a dynamic param to a Spring Data Postgres Native Query. The param is in an interval expression.

At the time of running the code, I verify from pgAdmin that the following returns 1 result only (correctly):

select * from recalls_t where created_date <= (now() - interval '18 hour')

PROBLEM:

1) In the Spring Data code, the following ?1 notation returns 2 results incorrectly:

@Query(value="select * from recalls_t where created_date <=  (now() - interval '?1 hour')", 
       nativeQuery=true)
public List<RecallsT> findActiveRecallsInLastHrs(@Param("hours") int hours);

2) Then I tried the solution in this thread: Postgres Interval not working with native spring data JPA query

They said to use a multiple of a single-unit interval. But this also returns 2 results incorrectly:

@Query(value="select * from recalls_t where created_date <=  (now() - 
       (interval '1 hour') * :hours)", 
       nativeQuery=true)
public List<RecallsT> findActiveRecallsInLastHrs(@Param("hours") int hours);

The only way I found to fix this is to hard-code the number "18" in my Spring Data query. So now there's no dynamic param, and I get 1 result correctly. None of the Dynamic Param implementations work.


回答1:


Try by passing a String ?

@Query(value="select * from recalls_t where created_date <=  (now() - interval ?1)", 
       nativeQuery=true)
public List<RecallsT> findActiveRecallsInLastHrs(String interval);

// ... 

findActiveRecallsInLastHrs("1 hour");


来源:https://stackoverflow.com/questions/57795441/postgres-interval-spring-data-dynamic-parameter-not-working

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