问题描述
我正在处理从 MysqL 到 Postgresql 的迁移。因此,我正在存储库中实现 Spring Data 查询。我遇到了以下 native 查询的问题:
@Query(value = "UPDATE some_table SET some_field= :someValue,changed_at=Now() WHERE (changed_at < Now() - INTERVAL :timeout MINUTE) LIMIT :limit",nativeQuery = true)
int updateRecords(@Param("someValue") String someValue,@Param("timeout") int timeoutMinutes,@Param("limit") int limit);
它在 MysqL 上运行良好,但在 Postgesql 中出现了错误:
org.springframework.dao.InvalidDataAccessResourceUsageException: Could not execute statement; sql [n/a]; nested exception is org.hibernate.exception.sqlGrammarException: Could not execute statement
...
Caused by: org.hibernate.exception.sqlGrammarException: Could not execute statement
...
Caused by: org.postgresql.util.PsqlException: ERROR: Syntax error at or near "$2"
解决方法
您不能以这种方式传递间隔的长度。
改用 make_interval()
更容易:
changed_at < now() - make_interval(mins => :timeout)
或者,如果 JPA 也在 =>
changed_at < now() - (interval '1 minute' * :timeout)