为了账号安全,请及时绑定邮箱和手机立即绑定

添加 X 小时 - @Query - Spring Data JPA

添加 X 小时 - @Query - Spring Data JPA

守着一只汪 2021-08-04 10:19:22
我尝试在 Spring Data JPA Repository 中创建一种不同的方法,该方法应该将给定的小时数添加到时间戳中。public interface ActivationCodeRepository extends CrudRepository<ActivationCode, Long> {  @Query(value = "select a from ActivationCode a where a.creationTime + INTERVAL '1 hour' * :hoursAgo  <=  CURRENT_TIMESTAMP and a.type = :type and a.account = account")  List<ActivationCode> getAllAddedAtLeastXHoursAgo(@Param("account") Account account, @Param("type") int type, @Param("hoursAgo") int hoursAgo);}它无法正常工作,因为它:间隔 '1 小时' * :hoursAgo确切地:'1小时'IDE 下划线并给出此错误:<'表达式'>、<'运算符'>、GROUP、HAVING 或 ORDER 预期。我试过做一些研究,并找到我应该如何将给定的时间添加到 creationTime 但在任何地方都找不到。
查看完整描述

3 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

我不相信 PostgreSQL 允许传递INTERVAL需要带有interval '1 day'-style 输入的硬编码字符串的 语句;但是,您可以通过将字符串转换为间隔来实现此目的。

尝试将代码中的 SQL 查询更改为:

select a from ActivationCode a where a.creationTime + (:hoursAgo||' hour')::interval <=  CURRENT_TIMESTAMP and a.type = :type and a.account = account

或者,我刚刚找到了以前的 StackOverflow 答案,这值得一试,但可能有同样的问题(假设它与 Spring Data JPA 的查询解析器有关):

select a from ActivationCode a where a.creationTime + :hoursAgo * INTERVAL '1 hour' <=  CURRENT_TIMESTAMP and a.type = :type and a.account = account



查看完整回答
反对 回复 2021-08-04
?
MM们

TA贡献1886条经验 获得超2个赞

就像a_horse_with_no_name说我必须使用本机查询来做类似的事情,所以我改变了我的方法:

  @Query(value = "select * from activation_codes a where a.type = :type and a.id_account = :id_account and a.creation_time <= NOW() - :hoursAgo * INTERVAL '1 hour'", nativeQuery = true)
  List<ActivationCode> getAllAddedAtLeastXHoursAgo(@Param("id_account") int id_account, @Param("type") int type, @Param("hoursAgo") int hoursAgo);

它工作正常。感谢所有帮助。


查看完整回答
反对 回复 2021-08-04
  • 3 回答
  • 0 关注
  • 206 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信