如何使用Hibernate映射java.time.Year和其他java.time类型

maa*_*nus 14 java hibernate java-8 java-time

hibernate-java8JAR了几个类似的类提供适配器Instant,LocalDate等等,但是从一些类java.time,例如Year,Month,YearMonth失踪.这些类被存储为未知的Serializable,这是不必要的浪费.

当然我可以使用int year而不是Year year,但我不认为,这是一个好主意.

看起来YearJavaDescriptor应该很容易写,但是,我想知道为什么它会丢失.特别是在情况下YearMonth,我非常喜欢现有的适配器,不是吗?或者我做了一些愚蠢的事情?

我不确定谷歌搜索没有返回任何东西.

naz*_*art 8

尝试创建一个转换器 - AttributeConverter为此目的实现.

我过去用过的东西如下:

@Entity
public class RealEstateAgency {
    @Column(name = "createdAt")
    @Convert(converter = ZonedDateTimeConverter.class)
    private ZonedDateTime creationDate;
}

@Converter(autoApply = true)
public class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, Date> {
 
    public Date convertToDatabaseColumn(ZonedDateTime toConvert) {
        return toConvert == null ? null : Date.from(toConvert.toInstant());
    }
 
    public ZonedDateTime convertToEntityAttribute(Date toConvert) {
        return toConvert == null ? null : ZonedDateTime.from(toConvert
                .toInstant());
    }
}
Run Code Online (Sandbox Code Playgroud)


Anu*_*tia 4

如果您的 JPA 提供程序没有以合理的方式持久保存类型(在本例中,因为它是 Java8 类,是在 JPA 2.1 获得批准后添加的),那么您需要定义一个 JPA 2.1 AttributeConverter 将其转换为标准 JPA 持久性类型(在本例中类似于 java.sql.Date)。