【问题标题】:How to use Java 8 Date library with Hibernate/JPA? [duplicate]如何在 Hibernate/JPA 中使用 Java 8 Date 库? [复制]
【发布时间】:2017-10-10 16:45:34
【问题描述】:

如何为我的 POJO 使用日期库?

我可以使用我的代码:

@Data
@Entity
@Table(name = "PERSON")
public class Person implements Serializable {

    private static final long serialVersionUID = -8041031461422721556L;

    @Id
    @Column(name = "PERSON_ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "DOB")
    private LocalDate dob;

}

我正在使用java.time.LocalDate 类型。

【问题讨论】:

  • errm,它是 JPA 2.2 的一部分。您的提供商还不支持 JPA 2.2 吗?
  • 对于 Hibernate,请参阅重复链接的 second answer

标签: java hibernate date jpa java-time


【解决方案1】:

目前 Hibernate/JPA 不兼容 Java 8 Date 库,但您只需要制作一个 AttributeConverter 即可使用该库:

对于 TIMESTAMP 类型,您可以使用此转换器:

@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime datetime) {
        return datetime == null ? null : Timestamp.valueOf(datetime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
        return timestamp == null ? null : timestamp.toLocalDateTime();
    }

}

对于 DATE 类型,您可以使用此转换器:

@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate date) {
        return date == null ? null : Date.valueOf(date);
    }

    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return date == null ? null : date.toLocalDate();
    }

}

对于 TIME 类型,您可以使用此转换器:

@Converter(autoApply = true)
public class LocalTimeAttributeConverter implements AttributeConverter<LocalTime, Time> {

    @Override
    public Time convertToDatabaseColumn(LocalTime time) {
        return time == null ? null : Time.valueOf(time);
    }

    @Override
    public LocalTime convertToEntityAttribute(Time time) {
        return time == null ? null : time.toLocalTime();
    }

}

【讨论】:

    猜你喜欢
    • 2015-03-01
    • 2023-03-19
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 2019-05-12
    • 2014-10-21
    相关资源
    最近更新 更多