Now that theJPA 2.2 Review Ballot was approved, let’s start analyzing some of the new additions to the standard which have been supported by Hibernate for quite some time already.
In this article, we are going to see how Java 8 Date/Time API is supported and which types you need to use depending on your business case requirements.
LocalDateTimeis rather straightforward since it only captures a point in time, similar to
OffsetDateTimeis more problematic because it only captures the offset, but not the time zone rules such as DST (Daylight Saving Time) or other rules defined by ZoneId and typically supported by
It’s also curious that the standard does not support the
java.time.Durationtype which can come in handy in many business use cases.
Considering we have following entities in our system:
Employeeentity contains the following Java 8 Date Time attributes:
attribute is a
since we are only interested in the Date part
since this attribute needs to store both Date and Time information
Meetingentity features the following Java 8 Date Time attributes:
which, even if not supported by JPA 2.2, is probably a more suitable version of
attribute might not be supported by JPA 2.2, but we will use it since Hibernate supports all these types
Assuming we persist the following entities:
Hibernate is going to generate the following SQL statements:
org.hibernate.type.descriptor.sql.TimestampTypeDescriptor, meaning that they are going to be persisted as
LocalDateTimeit makes no difference since, just like
java.sql.Timestamp, it only captures a time snapshot, the
ZonedDateTimeis going to lose the zone information.
When loading back our entities:
The original Java 8 Data Time objects match the ones being persisted.
If you enjoyed this article, I bet you are going to lovemy bookas well.
The reason why
ZonedDateTimeequals the one we previously saved is because the undnerlying
TIMESTAMPvalue was transposed in the current System Time Zone.
Until all JDBC Drivers will support
TIMESTAMP WITH TIMEZONEat the
java.sql.Statementparaeter value binding level which is a requirement forHHH-11773, it’s doubtful that you really need to use
Currently, it’s much wiser to save all
TIMESTAMPvalues inUTC, meaning that
LocalDateTimeis a much better fit for your JPA entities.
If you liked this article, you might want to subscribe tomy newsletter too.