问题描述
如何将带有Hibernate的Java 8 OffsetTime
和OffsetDateTime
保留为适当的SQL类型(TIME_WITH_TIMEZONE
和TIMESTAMP_WITH_TIMEZONE
)?我在博客中找到了使用EnhancedUserType
的LocalTime
和LocalDateTime
解决方案.
How can I persist Java 8 OffsetTime
and OffsetDateTime
with Hibernate as proper SQL types (TIME_WITH_TIMEZONE
and TIMESTAMP_WITH_TIMEZONE
)? I found a solution for LocalTime
and LocalDateTime
using EnhancedUserType
s in a blog.
偏移量数据的用户类型如何?
How would the user types be for offset data?
推荐答案
从2.2版开始,JPA提供了对 Java 8日期/时间API ,例如LocalDateTime
,LocalTime
,LocalDateTimeTime
,OffsetDateTime
或OffsetTime
.
Since version 2.2, JPA offers support for mapping Java 8 Date/Time API, like LocalDateTime
, LocalTime
, LocalDateTimeTime
, OffsetDateTime
or OffsetTime
.
此外,即使使用JPA 2.1,Hibernate 5.2默认也支持所有Java 8 Date/Time API.
Also, even with JPA 2.1, Hibernate 5.2 supports all Java 8 Date/Time API by default.
在Hibernate 5.1和5.0中,您必须添加hibernate-java8
Maven依赖项.
In Hibernate 5.1 and 5.0, you have to add the hibernate-java8
Maven dependency.
因此,假设我们具有以下Notification
实体:
So, let's assume we have the following Notification
entity:
@Entity(name = "Notification")
@Table(name = "notification")
public class Notification {
@Id
private Long id;
@Column(name = "created_on")
private OffsetDateTime createdOn;
@Column(name = "notify_on")
private OffsetTime clockAlarm;
//Getters and setters omitted for brevity
}
请注意,createdOn
属性是OffsetDateTime
Java对象,而clockAlarm
是OffsetTime
类型.
Notice that the createdOn
attribute is a OffsetDateTime
Java object and the clockAlarm
is of the OffsetTime
type.
坚持Notification
时:
ZoneOffset zoneOffset = ZoneOffset.systemDefault().getRules()
.getOffset(LocalDateTime.now());
Notification notification = new Notification()
.setId(1L)
.setCreatedOn(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
).atOffset(zoneOffset)
).setClockAlarm(
OffsetTime.of(7, 30, 0, 0, zoneOffset)
);
entityManager.persist(notification);
Hibernate生成正确的SQL INSERT语句:
Hibernate generates the proper SQL INSERT statement:
INSERT INTO notification (
notify_on,
created_on,
id
)
VALUES (
'07:30:00',
'2020-05-01 12:30:00.0',
1
)
在获取Notification
实体时,我们可以看到OffsetDateTime
和OffsetTime
是从数据库中正确提取的:
When fetching the Notification
entity, we can see that the OffsetDateTime
and OffsetTime
are properly fetched from the database:
Notification notification = entityManager.find(
Notification.class, 1L
);
assertEquals(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
).atOffset(zoneOffset),
notification.getCreatedOn()
);
assertEquals(
OffsetTime.of(7, 30, 0, 0, zoneOffset),
notification.getClockAlarm()
);
这篇关于如何使用JPA和Hibernate保持OffsetTime和OffsetDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!