java – Persist OffsetTime和OffsetDateTime

如何将Java 8 OffsetTime和OffsetDateTime与Hibernate一起保存为正确的SQL类型(TIME_WITH_TIMEZONE和TIMESTAMP_WITH_TIMEZONE)?我在a blog中使用EnhancedUserTypes找到了LocalTime和LocalDateTime的解决方案.

用户类型如何用于偏移数据?

最佳答案
从Hibernate开始,ORM 5.3实现了JPA 2.2标准.

JPA 2.2规范说现在支持以下Java 8类型:

> java.time.LocalDate
> java.time.LocalTime
> java.time.LocalDateTime
> java.time.OffsetTime
> java.time.OffsetDateTime

因此,您可以使用表的时间戳作为示例:

您拥有的实体:


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

            @Id
            private Integer id;

            @Column(name = "duration_value")
            private Duration duration = Duration.of( 20, ChronoUnit.DAYS );

            @Column(name = "instant_value")
            private Instant instant = Instant.now();

            @Column(name = "local_date")
            private LocalDate localDate = LocalDate.now();

            @Column(name = "local_date_time")
            private LocalDateTime localDateTime = LocalDateTime.now();

            @Column(name = "local_time")
            private LocalTime localTime = LocalTime.now();

            @Column(name = "offset_date_time")
            private OffsetDateTime offsetDateTime = OffsetDateTime.now();

            @Column(name = "offset_time")
            private OffsetTime offsetTime = OffsetTime.now();

            @Column(name = "zoned_date_time")
            private ZonedDateTime zonedDateTime = ZonedDateTime.now();

            //Getters and setters omitted for brevity
    }

关联的数据库表将是:


    create table DateTimeEntity
    (
        id                  integer not null,
        duration_value      bigint,
        instant_value       timestamp,
        local_date          date,
        local_date_time     timestamp,
        local_time          time,
        offset_date_time    timestamp,
        offset_time         time,
        zoned_date_time     timestamp,
        primary key (id)
    )

参考:http://in.relation.to/2018/02/20/java8-date-time-mapping/

转载注明原文:java – Persist OffsetTime和OffsetDateTime - 代码日志