How to persist LocalDate with JPA?
With JPA 2.2, you no longer need to use converter it added support for the mapping of the following java.time types:
java.time.LocalDate
java.time.LocalTime
java.time.LocalDateTime
java.time.OffsetTime
java.time.OffsetDateTime
@Column(columnDefinition = "DATE")
private LocalDate date;
@Column(columnDefinition = "TIMESTAMP")
private LocalDateTime dateTime;
@Column(columnDefinition = "TIME")
private LocalTime localTime;
JPA 2.2 supports LocalDate
, so no converter is needed.
Hibernate also supports it as of 5.3 version.
Check out this article for more details.
JPA 2.2 added support for mapping Java 8 Date/Time API, like LocalDate
, LocalTime
, LocalDateTime
, OffsetDateTime
or OffsetTime
.
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 LocalDate subscribedOn;
//Getters and setters omitted for brevity
}
Notice that the subscribedOn
attribute is a LocalDate
Java object.
When persisting the UserAccount
:
UserAccount user = new UserAccount()
.setId(1L)
.setFirstName("Vlad")
.setLastName("Mihalcea")
.setSubscribedOn(
LocalDate.of(
2013, 9, 29
)
);
entityManager.persist(user);
Hibernate generates the proper SQL INSERT statement:
INSERT INTO user_account (
first_name,
last_name,
subscribed_on,
id
)
VALUES (
'Vlad',
'Mihalcea',
'2013-09-29',
1
)
When fetching the UserAccount
entity, we can see that the LocalDate
is properly fetched from the database:
UserAccount userAccount = entityManager.find(
UserAccount.class, 1L
);
assertEquals(
LocalDate.of(
2013, 9, 29
),
userAccount.getSubscribedOn()
);
Hibernate 5 supports java 8, so you can add this to your pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>5.1.0.Final</version>
</dependency>
This gives you mapping for LocalDate
and LocalDateTime
out of box.