【问题标题】:Java Spring/PgSQL operation with timestamp returns interval带有时间戳的 Java Spring/PgSQL 操作返回间隔
【发布时间】:2020-06-21 05:26:36
【问题描述】:

我正在尝试使用 Postgresql 数据库在 Java Spring 上的时间戳间隔内检索数据。 我正在使用的查询之一,工作得很好(它返回过去 24 小时的数据):

  @Query(value = "SELECT timestamp,lettura,stato FROM dati_impianti 
WHERE sigla_impianto = :impianto and timestamp > now() - interval '24 hours' 
ORDER BY timestamp DESC", nativeQuery = true)
  List<ReadingEntity> findLastDay(@Param("impianto") String s);

但是,当我尝试返回具有不同时间戳的数据时,我得到一个 PSQL 异常:

 @Query(value = "SELECT timestamp,lettura,stato FROM dati_impianti 
WHERE sigla_impianto = :impianto and timestamp > :timestamp - interval '24 hours' 
ORDER BY timestamp DESC", nativeQuery = true)
  List<ReadingEntity> findDate(@Param("impianto") String s, @Param("timestamp") Timestamp t);

这是我得到的例外:

org.postgresql.util.PSQLException: ERROR: operator does not exist: timestamp without time zone > interval
No operator matches the given name and argument types. You might need to add explicit type casts.

我无法理解的是,根据 PostgreSQL 文档,timestamp - interval 应该返回另一个 timestamp。但是,从我的查询来看,我似乎将 timestamp(来自表)与 interval 进行比较,这是错误的。如果我尝试直接使用我的时间戳参数(以 timestamp > :timestamp 的形式而不将其减少一个间隔),它可以工作,但它不是我想要的。

我也尝试过显式转换,使用 :timestamp::timestamp 但这似乎给出了另一种错误,因为 Spring 及其处理参数的方式。

【问题讨论】:

    标签: java spring postgresql spring-boot spring-mvc


    【解决方案1】:

    您可能想尝试将参数显式转换为timestamp

    where 
        sigla_impianto = :impianto 
        and timestamp > :timestamp::timestamp - interval '24 hours'
    

    或者,可能:

    where 
        sigla_impianto = :impianto 
        and timestamp > cast(:timestamp as timestamp) - interval '24 hours'
    

    【讨论】:

    • 感谢您的回答。正如我在我的问题上所说,由于某种原因,这似乎不起作用,因为我得到一个 java.lang.IllegalArgumentException:无法找到命名参数 [timestamp],期待 [impianto,timestamp::timestamp] 之一
    • @Mastarius:我在答案中添加了另一种语法。
    • 谢谢,这种替代的显式转换方法似乎可以解决问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2018-10-25
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多