我有一个实体,它扩展了一个名为 AbstractAuditingEntity 的审计实体类,其中一个字段是
@CreatedDate
@Column(name = "created_date", nullable = false)
@JsonIgnore
private ZonedDateTime createdDate
以上字段已映射到名为 "created_date"
且类型为 "timestamp without time zone"
的数据库字段。
但是在保存这个实体时 PostgresSQL 抛出如下错误:
Caused by: org.postgresql.util.PSQLException: ERROR: column "created_date" is of type timestamp without time zone but expression is of type bytea
Hint: You will need to rewrite or cast the expression.
我在此处查找了相同的错误并找到了解决方案:Postgresql UUID supported by Hibernate?
但是解决方案是针对java.util.UUID
,在解决方案中建议在字段上添加注解@Type(type="pg-uuid")
使用 UUID 类型。
ZonedDateTime
是否有像 pg-uuid
这样的现成类型值? hibernate @Type
注释的不同值常量的任何引用链接?
或者我应该编写自定义反序列化器类?如何编写这样的反序列化器类任何引用链接?
PostgresSQL Version : 9.6,
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
最佳答案
对于 Hibernate 5.2,它应该开箱即用。
对于 5.0 你可以添加一个依赖来支持它:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>${hibernate.version}</version>
</dependency>
对于 4.3,您可以使用 JPA 2.1 转换器:
@Converter
public class TimestampConverter implements AttributeConverter<ZonedDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(ZonedDateTime zonedTime) {
if (zonedTime == null) {
return null;
}
return new Timestamp(zonedTime.toInstant().toEpochMilli());
}
@Override
public ZonedDateTime convertToEntityAttribute(Timestamp localTime) {
if (localTime == null) {
return null;
}
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(localTime.getTime()), ZoneId.systemDefault());
}
}
然后用@Convert
注释你的属性:
@Convert(converter = TimestampConverter.class)
private ZonedDateTime createdDate;
我注意到您的数据库列是 TIMESTAMP
。它实际上应该是 TIMESTAMP WITH TIME ZONE
,特别是如果您的客户端时区有夏令时更改。
关于java - 无法使用 hibernate PostgreSQL 存储 java.time.ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41712888/