Spring Boot + Spring Data JPA + Java 8 date and time (JSR310)
By:Roy.LiuLast updated:2019-08-11
In Spring Boot + Spring Data JPA application, to support the JSR310 java.time.* APIs, we need to register this Jsr310JpaConverters manually.
import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; @EntityScan( basePackageClasses = {Application.class, Jsr310JpaConverters.class} @SpringBootApplication public class Application { //...
P.S Tested with Spring Boot 1.5.1.RELEASE, Spring Data JPA 1.11.0.RELEASE
1. Full Example
1.1 A model contains a java.time.LocalDate field.
package com.mkyong.model; import javax.persistence.*; import java.time.LocalDate; @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CUST_SEQ") @SequenceGenerator(sequenceName = "customer_seq", allocationSize = 1, name = "CUST_SEQ") Long id; String name; @Column(name = "CREATED_DATE") LocalDate date; //...
1.2 @EntityScan to scan and register Jsr310JpaConverters like this :
package com.mkyong; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; import java.util.Arrays; //for jsr310 java 8 java.time.* @EntityScan( basePackageClasses = {Application.class, Jsr310JpaConverters.class} @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); @Bean public CommandLineRunner run(ApplicationContext appContext) { return args -> { System.out.println("hello World!"); };
References
- Jsr310JpaConverters JavaDoc
- JSR 310: Date and Time API
- Spring Data MongoDB + JSR-310 or Java 8 new Date APIs
From:一号门
COMMENTS