gpt4 book ai didi

java - 使用 Spring Data JDBC 不支持的查询参数类型?

转载 作者:行者123 更新时间:2023-12-02 02:19:41 25 4
gpt4 key购买 nike

我尝试在我的存储库中编写与此类似的查询方法

@Modifying
@Query("UPDATE foo SET some_timestamp = :someTimestamp WHERE id = :id")
void updateSomeTimestamp(@Param("id") long id, @Param("someTimestamp") Instant someTimestamp)

执行代码时出现以下错误:

org.postgresql.util.PSQLException:无法推断用于 java.time.Instant 实例的 SQL 类型。使用带有显式 Types 值的 setObject() 来指定要使用的类型。

我是否忘记了什么,或者 Spring Data Jdbc 根本不支持使用 Instant 作为参数?如果有,将来是否计划提供此类支持?

最佳答案

对于那些来这里寻找解决方案来生成精度高于毫秒的 java.sql.Timestamp 实例的人(不推荐使用接受 nanos 的 Timestamp 构造函数):

时间戳时间戳 = Timestamp.from(Instant.now());

这假设您的操作系统支持高于毫秒的系统时钟精度。它对于支持优于毫秒的 TIMESTAMP 精度的数据库非常有用,例如支持微秒精度的 PostgreSQL。

您可以将其转换回 InstantLocalDateTime:

System.out.println(timestamp.toInstant());//世界标准时间

System.out.println(timestamp.toLocalDateTime());//本地时间

我还将重申 stoetti 在评论中提供的信息,根据 stoetti 提供的文档链接, https://jdbc.postgresql.org/documentation/head/8-date-time.html ,PostgreSQL JDBC 驱动程序确实将以下 java.time 类识别为时间戳:

java.time.LocalTime as TIME [没有时区]

java.time.LocalDateTime as TIMESTAMP [没有时区]

java.time.OffsetDateTime 作为带有时区的时间戳

但不是 java.time.Instant,正如斯托蒂指出的那样。

关于java - 使用 Spring Data JDBC 不支持的查询参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59404071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com