java - 无法使用 hibernate PostgreSQL 存储 java.time.ZonedDateTime

标签 java spring postgresql hibernate

我有一个实体,它扩展了一个名为 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/

相关文章:

java - 当返回的对象之一为 null 时,Java If 语句的缩写形式返回 NullPointerException

Java 记录器 - "No line break"和 "explicit class logging"问题

mysql - bool 值的 Postgres 和 MySql 之间的返回值差异

python - 编程错误 : column "product" is of type product[] but expression is of type text[] enum postgres

java - 在 jhipster 项目中正确配置我的 smtp 设置

postgresql - Postgres 隧道 SSH -L 在后台

java - 如何将包含对象数组的 JSON 对象发送到 spring Controller ?

java - 如何在AsyncTask类中添加更多方法?

java - 为什么我的 Spring @Autowired 字段为空?

java - org.hibernate.ObjectDeletedException : deleted object would be re-saved by cascade : Error while trying to delete a Patient object