JPA 2.2 offers support for mapping Java 8 Date/Time API, likebut only for the following types:
However, Hibernate supports also ZonedDateTime, LocalTime, ZonedDateTimeTime, 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 ZonedDateTime subscribedOn; //Getters and setters omitted for brevity }
Notice that the subscribedOn attribute is a ZonedDateTime 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 ).atZone(ZoneId.systemDefault()) ); 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 ZonedDateTime is properly fetched from the database:
UserAccount userAccount = entityManager.find( UserAccount.class, 1L ); assertEquals( LocalDateTime.of( 2020, 5, 1, 12, 30, 0 ).atZone(ZoneId.systemDefault()), userAccount.getSubscribedOn() );