Hibernate 5无法正确处理LocalDate

时间:2015-12-10 16:24:36

标签: java hibernate datetime java-8 hibernate-5.x

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

该属性声明如下:

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

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

有没有办法配置Hibernate来禁用这种行为(除了实现一个特殊的属性编写器)?

1 个答案:

答案 0 :(得分:3)

确实是一个错误。我在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