JPA and Hibernate: Persist LocalDate and LocalDateTime [Video]
As useful as JPA is, you still run into problems when using it with Java 8's updated Date and Time API. Here's how to build an AttributeConverter and how Hibernate helps.
Join the DZone community and get the full member experience.
Join For FreeJava 8 brought lots of great features, and one of the most important and most anticipated ones was the Date and Time API. There were lots of issues with the old API — I won’t get into any details on why we needed a new one. I’m sure you had to struggle often enough with it yourself.
All these issues were gone with Java 8. The new Date and Time API is well-designed, easy to use, and (finally) immutable. The only issue that remains is that you cannot use it with JPA.
Well, that’s not completely correct. You can use it, but JPA will map it to a BLOB instead of a DATE or TIMESTAMP. That means the database is not aware of the date object and cannot apply any optimization for it. That’s not the way we should or want to do it.
But that doesn’t mean that you can’t use the Date and Time API. You just have to decide how you want to add the support for it. You either use Hibernate 5, which provides proprietary support for the Date and Time API, or you take a few minutes to implement an AttributeConverter like I show you in this post.
Why Does JPA Not Support LocalDate and LocalDateTime?
The answer is simple, JPA 2.1 was released before Java 8 and the Date and Time API simply didn’t exist at that point in time. Therefore, the @Temporal annotation can only be applied to attributes of type java.util.Date and java.util.Calendar.
If you want to store a LocalDate attribute in a DATE column or a LocalDateTime in a TIMESTAMP column, you need to define the mapping to java.sql.Date or java.sql.Timestamp yourself. Thanks to the attribute converter, one of several new features in JPA 2.1, this can be achieved with just a few lines of code.
In the following video, I will show you how to create an attribute converter for LocalDateand LocalDateTime. If you want to learn more about attribute converter, have a look at How to implement a JPA 2.1 Attribute Converter or one of the other usage examples like a better way to persist enums or encrypting data.
The most important things you need to remember about attribute converter are also described in the free “New Features in JPA 2.1” cheat sheet.
Published at DZone with permission of Thorben Janssen, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments