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

我尝试在 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 但在任何地方都找不到。


守着一只汪
浏览 207回答 3
3回答

米琪卡哇伊

我不相信 PostgreSQL 允许传递INTERVAL需要带有interval '1 day'-style 输入的硬编码字符串的&nbsp;语句;但是,您可以通过将字符串转换为间隔来实现此目的。尝试将代码中的 SQL 查询更改为:select&nbsp;a&nbsp;from&nbsp;ActivationCode&nbsp;a&nbsp;where&nbsp;a.creationTime&nbsp;+&nbsp;(:hoursAgo||'&nbsp;hour')::interval&nbsp;<=&nbsp;&nbsp;CURRENT_TIMESTAMP&nbsp;and&nbsp;a.type&nbsp;=&nbsp;:type&nbsp;and&nbsp;a.account&nbsp;=&nbsp;account或者,我刚刚找到了以前的 StackOverflow 答案,这值得一试,但可能有同样的问题(假设它与 Spring Data JPA 的查询解析器有关):select&nbsp;a&nbsp;from&nbsp;ActivationCode&nbsp;a&nbsp;where&nbsp;a.creationTime&nbsp;+&nbsp;:hoursAgo&nbsp;*&nbsp;INTERVAL&nbsp;'1&nbsp;hour'&nbsp;<=&nbsp;&nbsp;CURRENT_TIMESTAMP&nbsp;and&nbsp;a.type&nbsp;=&nbsp;:type&nbsp;and&nbsp;a.account&nbsp;=&nbsp;account

MM们

就像a_horse_with_no_name说我必须使用本机查询来做类似的事情,所以我改变了我的方法:&nbsp;&nbsp;@Query(value&nbsp;=&nbsp;"select&nbsp;*&nbsp;from&nbsp;activation_codes&nbsp;a&nbsp;where&nbsp;a.type&nbsp;=&nbsp;:type&nbsp;and&nbsp;a.id_account&nbsp;=&nbsp;:id_account&nbsp;and&nbsp;a.creation_time&nbsp;<=&nbsp;NOW()&nbsp;-&nbsp;:hoursAgo&nbsp;*&nbsp;INTERVAL&nbsp;'1&nbsp;hour'",&nbsp;nativeQuery&nbsp;=&nbsp;true) &nbsp;&nbsp;List<ActivationCode>&nbsp;getAllAddedAtLeastXHoursAgo(@Param("id_account")&nbsp;int&nbsp;id_account,&nbsp;@Param("type")&nbsp;int&nbsp;type,&nbsp;@Param("hoursAgo")&nbsp;int&nbsp;hoursAgo);它工作正常。感谢所有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java