将 TIMESTAMP 列从 PostgreSQL 映射到 LocalDate

ip6*_*696 4 java timestamp hibernate localdate

我在实体中有字段:

@Column(name = "BILL_DATE")
private LocalDate billDate;
Run Code Online (Sandbox Code Playgroud)

我的系统与oracle和 一起工作posthresql。在 posgresql 中,此列具有类型,timestamp但在 oracle - 中date。当我尝试启动服务器时postgeSQL出现错误:

wrong column type encountered in column [bill_date] in table [charges]; found [timestamp (Types#TIMESTAMP)], but expecting [date (Types#DATE)]
Run Code Online (Sandbox Code Playgroud)

如果我添加注释,@Temporal(TemporalType.DATE)我会收到另一个错误:

Caused by: org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property
Run Code Online (Sandbox Code Playgroud)

但我不想使用java.util.Date和java.util.Calendar。如何解决这个问题呢?

Rub*_*nDG 7

无论在甲骨文日期和时间戳PostgreSQL中存储日期和时间。实际上,根据PostgreSQL 文档,如果时间戳不包含时区,您应该将它们映射到LocalDateTime,或者如果它与时区一起映射到OffsetDateTime。

Hibernate 5 应该支持 Java8 Time API,反正如果你使用 JPA,你可以实现 AttributeConverter

import javax.persistence.AttributeConverter;
import java.sql.Timestamp;
import java.time.LocalDate;

public class LocalDateConverter implements AttributeConverter < LocalDate, Timestamp > {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDate attribute) {
        return attribute != null ? Timestamp.valueOf(attribute.atStartOfDay()) : null;
    }

    @Override
    public LocalDate convertToEntityAttribute(Timestamp dbData) {
        return dbData != null ? dbData.toLocalDateTime().toLocalDate() : null;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

@Convert(converter = LocalDateConverter.class)
@Column(name = "BILL_DATE")
private LocalDate billDate;
Run Code Online (Sandbox Code Playgroud)