gpt4 book ai didi

java - 如何使用 JPA 和 Hibernate 保留 OffsetTime 和 OffsetDateTime?

转载 作者:搜寻专家 更新时间:2023-11-01 03:36:47 28 4
gpt4 key购买 nike

如何将 Java 8 OffsetTimeOffsetDateTime 与 Hibernate 保持为正确的 SQL 类型(TIME_WITH_TIMEZONETIMESTAMP_WITH_TIMEZONE )?

我在 a blog 中使用 EnhancedUserType 找到了 LocalTimeLocalDateTime 的解决方案| .

offset 数据的用户类型如何?

最佳答案

Hibernate ORM 5.3 实现了 JPA 2.2 标准。


Java 8 Date and Time API 中支持的类型

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

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

Hibernate ORM 支持所有这些类型,甚至更多:

  • java.time.ZonedDateTime
  • java.time.Duration

实体映射

假设您有以下实体:

@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
}

DateTimeEntity 将有一个关联的数据库表,如下所示:

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)
)

来源:Mapping Java 8 Date/Time entity attributes with Hibernate

关于java - 如何使用 JPA 和 Hibernate 保留 OffsetTime 和 OffsetDateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211210/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com