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 entity:
@Entity(name = "UserAccount")
@Table(name = "user_account")
public class UserAccount {
@Id
private Long id;
@Column(name = "first_name", length = 50)
private String firstName;
@Column(name = "last_name", length = 50)
private String lastName;
@Column(name = "subscribed_on")
private LocalDateTime subscribedOn;
//Getters and setters omitted for brevity
}
Notice that the subscribedOn
attribute is a LocalDateTime
Java object.
When persisting the UserAccount
:
UserAccount user = new UserAccount()
.setId(1L)
.setFirstName("Vlad")
.setLastName("Mihalcea")
.setSubscribedOn(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
)
);
entityManager.persist(user);
Hibernate generates the proper SQL INSERT statement:
INSERT INTO user_account (
first_name,
last_name,
subscribed_on,
id
)
VALUES (
'Vlad',
'Mihalcea',
'2020-05-01 12:30:00.0',
1
)
When fetching the UserAccount
entity, we can see that the LocalDateTime
is properly fetched from the database:
UserAccount userAccount = entityManager.find(
UserAccount.class, 1L
);
assertEquals(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
),
userAccount.getSubscribedOn()
);