将TIMESTAMP列从PostgreSQL映射到LocalDate

时间:2018-10-29 08:01:42

标签: java hibernate timestamp localdate

我在Entity中有一个字段:

@Column(name = "BILL_DATE")
private LocalDate billDate;

我的系统可以使用oracleposthresql。在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)]

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

Caused by: org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property

但是我不想使用java.util.Datejava.util.Calendar如何解决此问题?

1 个答案:

答案 0 :(得分:1)

Date in OracleTimestamp in PostgreSQL都存储日期。实际上,根据PostgreSQL Documentation,如果时间戳不包含时区,则应将它们映射到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;
    }

}

然后您可以使用

@Convert(converter = LocalDateConverter.class)
@Column(name = "BILL_DATE")
private LocalDate billDate;
相关问题