带时间戳返回间隔的 Java Spring/PgSQL 操作

标签 java spring postgresql spring-boot spring-mvc

我正在尝试使用 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 > :timestamp 的形式,而不将其减少一个时间间隔),它可以工作,但不是我想要的。

我还尝试使用 :timestamp::timestamp 进行显式强制转换,但这似乎会由于 Spring 及其处理参数的方式而产生另一种错误。

最佳答案

您可能想尝试将参数显式转换为时间戳:

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 Spring/PgSQL 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60598586/

相关文章:

java - 在intellij idea中运行GUI应用程序

java - Spring Boot通过MessageConverters序列化Instant

java - 如何使用 <Integer,HashMap<Integer,Integer> 的 HashMap 添加增量值

java - getRealPath ("/") 在 spring boot 中不工作

sql - 从表中存储表名的表中查询

postgresql - 与没有函数包装器的查询相比,SQL 函数非常慢

java - 如何将文件从服务器linux传输到另一台服务器linux java代码

java - 当可以导入 java 类时为什么要使用依赖注入(inject)?

java - 为新的 Spring MVC 项目选择 Thymeleaf 和 A​​ngular

database - PostgreSQL - Slony > fatal error : duplicate key value violates unique constraint "sl_nodelock-pkey"