Hibernate 5 不能正确处理 LocalDate

Hibernate 5 doesn't handle LocalDate properly

我们正在将 Hibernate (5.0.2) 代码迁移到 Java 8,这还涉及从 java.util.Datejava.time.LocalDate 的转换(以解决与日期处理相关的问题Java 7).我 运行 遇到的问题之一是 Hibernate 如何处理我们用作 "zero date" 的特殊值,即 0001-01-01.

属性声明如下:

@NotNull
@Column(name = "START_DATE", nullable = false)
private LocalDate startDate;

该值在数据库中存储为 0001-01-01,但是当它被 Hibernate 加载时它突然变成 0000-12-29。我假设发生这种情况是因为 Hibernate 默认使用公历,并且由于这个日期是在它被引入之前,所以使用了一些转换。

有什么方法可以配置 Hibernate 以禁用此行为(除了实现特殊的 属性 writer 之外)?

确实是个bug。我在 the following test 中复制了它。我将为它打开一个错误报告。

如果我使用 LocalDate:

@Entity(name = "LocalDateEvent")
public class LocalDateEvent {

    @Id
    private Long id;

    @NotNull
    @Column(name = "START_DATE", nullable = false)
    private LocalDate startDate;
}

和运行这个测试:

doInJPA(entityManager -> {
    LocalDateEvent event = new LocalDateEvent();
    event.id = 1L;
    event.startDate = LocalDate.of(1, 1, 1);
    entityManager.persist(event);
});

doInJPA(entityManager -> {
    LocalDateEvent event = entityManager.find(LocalDateEvent.class, 1L);
    assertEquals(LocalDate.of(1, 1, 1), event.startDate);
});

我得到:

java.lang.AssertionError: expected:<0001-01-01> but was:<0000-12-29>

Jira issue is here.

它对 OffsetDateTime 也不起作用:

@Entity(name = "OffsetDateTimeEvent")
public static class OffsetDateTimeEvent {

    @Id
    private Long id;

    @NotNull
    @Column(name = "START_DATE", nullable = false)
    private OffsetDateTime startDate;
}

和运行进行此测试:

doInJPA(entityManager -> {
    OffsetDateTimeEvent event = new OffsetDateTimeEvent();
    event.id = 1L;
    event.startDate = OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
    entityManager.persist(event);
});

doInJPA(entityManager -> {
    OffsetDateTimeEvent event = entityManager.find(OffsetDateTimeEvent.class, 1L);
    assertEquals(OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC), event.startDate);
});

投掷:

java.lang.AssertionError: expected:<0001-01-01T00:00Z> but was:<0001-01-01T01:34:52+01:34:52>

Jira issue for this is here.