How to persist JSR-310 types with Spring Data JPA?

后端 未结 3 1801
死守一世寂寞
死守一世寂寞 2020-11-28 05:33

I am trying to use Spring Data JPA 1.8 with the Java 8 Date/Time API JSR-310.

Everything seems to work, until I try to get all Vehicles between two LocalDateTimes. T

相关标签:
3条回答
  • 2020-11-28 05:43

    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 { … }
    
    0 讨论(0)
  • 2020-11-28 05:48

    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 Types 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)

    0 讨论(0)
  • 2020-11-28 05:53

    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

    0 讨论(0)
提交回复
热议问题