Hibernate 6如何将Instant字段映射为无时区Timestamp?
解决Hibernate 6将Instant映射为带时区timestamp的问题
全局配置(推荐)
在Spring Boot的application.properties中添加以下配置,全局修改Instant字段的默认JDBC类型映射:
spring.jpa.properties.hibernate.type.preferred_instant_jdbc_type=TIMESTAMP
这个配置会让Hibernate 6将所有Instant类型字段映射为PostgreSQL的timestamp without time zone,和Hibernate 5的原有行为完全一致,无需逐个修改实体字段。
单个字段配置
如果不需要全局修改,或者全局配置不生效,可以在实体类的Instant字段上显式指定列定义:
import jakarta.persistence.Column; import java.time.Instant; // ... @Column(columnDefinition = "timestamp without time zone") private Instant updateTime;
由于PostgreSQL中timestamp默认等价于timestamp without time zone,也可以简化为:
@Column(columnDefinition = "timestamp") private Instant updateTime;
原生Hibernate配置(非Spring Boot场景)
如果使用原生Hibernate配置(如persistence.xml),添加以下属性:
<property name="hibernate.type.preferred_instant_jdbc_type" value="TIMESTAMP"/>
补充说明
之前尝试的spring.jpa.properties.hibernate.jdbc.time_zone=UTC仅用于控制Java时间对象与数据库之间的时区转换逻辑,不会改变Hibernate生成的数据库字段类型,因此无法解决这个问题。Hibernate 6对Instant类型的默认映射规则做了调整,默认使用TIMESTAMP_WITH_TIMEZONE,通过上述配置可以强制改回原有映射逻辑。
内容的提问来源于stack exchange,提问作者NazgulCZ
相关产品推荐
相关产品推荐

