Since version 2.2, JPA offers support for mapping Java 8 Date/Time API, like LocalDateTime
, LocalTime
, LocalDateTimeTime
, OffsetDateTime
or OffsetTime
.
Also, even with JPA 2.1, Hibernate 5.2 supports all Java 8 Date/Time API by default.
In Hibernate 5.1 and 5.0, you have to add the hibernate-java8
Maven dependency.
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
}
Notice that the createdOn
attribute is a OffsetDateTime
Java object and the clockAlarm
is of the OffsetTime
type.
When persisting the 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 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
)
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()
);