我嘗試在 Spring Data JPA Repository 中創(chuàng)建一種不同的方法,該方法應(yīng)該將給定的小時(shí)數(shù)添加到時(shí)間戳中。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);}它無(wú)法正常工作,因?yàn)樗洪g隔 '1 小時(shí)' * :hoursAgo確切地:'1小時(shí)'IDE 下劃線并給出此錯(cuò)誤:<'表達(dá)式'>、<'運(yùn)算符'>、GROUP、HAVING 或 ORDER 預(yù)期。我試過(guò)做一些研究,并找到我應(yīng)該如何將給定的時(shí)間添加到 creationTime 但在任何地方都找不到。
3 回答

米琪卡哇伊
TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
我不相信 PostgreSQL 允許傳遞INTERVAL
需要帶有interval '1 day'
-style 輸入的硬編碼字符串的 語(yǔ)句;但是,您可以通過(guò)將字符串轉(zhuǎn)換為間隔來(lái)實(shí)現(xiàn)此目的。
嘗試將代碼中的 SQL 查詢更改為:
select a from ActivationCode a where a.creationTime + (:hoursAgo||' hour')::interval <= CURRENT_TIMESTAMP and a.type = :type and a.account = account
或者,我剛剛找到了以前的 StackOverflow 答案,這值得一試,但可能有同樣的問(wèn)題(假設(shè)它與 Spring Data JPA 的查詢解析器有關(guān)):
select a from ActivationCode a where a.creationTime + :hoursAgo * INTERVAL '1 hour' <= CURRENT_TIMESTAMP and a.type = :type and a.account = account

MM們
TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
就像a_horse_with_no_name說(shuō)我必須使用本機(jī)查詢來(lái)做類似的事情,所以我改變了我的方法:
@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);
它工作正常。感謝所有幫助。
添加回答
舉報(bào)
0/150
提交
取消