Search code examples
spring-bootjacksonlocaldate

spring boot, jackson and localdate


I use spring boot with mysql

in my application.properties

spring.jpa.generate-ddl=true
spring.jackson.serialization.write-dates-as-timestamps=false

In my build.gradle I have

compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-data-rest')
compile('org.springframework.boot:spring-boot-starter-web')
compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'

In my java class

import java.time.LocalDate;

@Entity
public class WebSite implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long webSiteId;

    private LocalDate date;
    ...
}

When this table is created,

date field is created like a TINYBLOB

Why is not a date


Solution

  • This is not an issue with Jackson, but rather that whatever you are using for ORM doesn't know how to convert a Java LocalDate to a MySQL Date.

    There are two ways to do this. If you are using Hibernate, you simply include org.hibernate:hibernate-java8 in your dependencies.

    Alternatively, if you want just use JPA, you need to create an Attribute Converter. For example:

    @Converter(autoApply = true)
    public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
    
        @Override
        public Date convertToDatabaseColumn(LocalDate locDate) {
            return (locDate == null ? null : Date.valueOf(locDate));
        }
    
        @Override
        public LocalDate convertToEntityAttribute(Date sqlDate) {
            return (sqlDate == null ? null : sqlDate.toLocalDate());
        }
    }
    

    The Attribute Converter will handle converting between a Java LocalDate and MySQL Date.

    See: http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/