How to persist JSR-310 types with Spring Data JPA?
Solution 1:
UPDATE: The answer below is valid if you need to stay on a Hibernate version < 5.0. Hibernate 5.0 supports persisting JSR-310 date/time types out of the box. I.e. if you are on Hibernate 5.0 or newer, Adam's answer is the way to go. Everyone else, read on.
The root cause for this at none of the widely used JPA providers actually support JSR-310 types out of the box yet. However, as of Spring Data JPA 1.8.0 we ship JPA 2.0 converters that will translate non-time-zoned JSR-310 types into a legacy Date
so that they can be persisted as is.
To get this working, simply register org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters
as one of the managed JPA classes with your provider. There's a couple of way to do that: in a very standard JPA setup you list it in your persistence.xml
. In a LocalContainerEntityManagerFactoryBean
based setup you can just add the package of the class to the packagesToScan
property. If you're using Spring Boot adding the class to the @EntityScan
annotation does the trick.
The latter is described in a bit more detail in the blog post covering the new features the Spring Data release train named Fowler ships
Solution 2:
When using Hibernate >=5.0, <5.2, you can drop in
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>${hibernate.version}</version>
</dependency>
on your classpath which will automatically register Type
s corresponding to the JSR310 classes.
(Thanks @AbhijitSarkar) Since 5.2, "the hibernate-java8 module has been merged into hibernate-core and the Java 8 date/time types are now natively supported." (Migration Guide 5.2)
Solution 3:
It took me quite a while to figure out how to use LocalDateTime
in my JPA Entity. I was on the latest Spring boot version. And debugged a lot into the ConversionServices.
Oliver Gierkes answer helped me a lot in getting to the final working setup:
Add Spring-data-jpa 1.8.0 or higher to your dependency management
compile("org.springframework.data:spring-data-jpa:1.8.2.RELEASE")
Enable @EntityScan for the Jsr310JpaConverters + (at least) your Application.class
@EntityScan(
basePackageClasses = { Application.class, Jsr310JpaConverters.class }
)
@SpringBootApplication
class Application { … }