spring boot, jackson and localdate



>我将 spring boot 与 mysql 一起使用

在我的应用程序中。

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

在我的build.gradle中,我有

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'

在我的 Java 类中

import java.time.LocalDate;

@Entity
public class WebSite implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long webSiteId;
    private LocalDate date;
    ...
}

创建此表时,

日期字段像 TINYBLOB 一样创建

为什么不是日期

这不是杰克逊的问题,而是无论你用于ORM的任何东西都不知道如何将Java LocalDate转换为MySQL Date。

有两种方法可以做到这一点。如果您使用的是 Hibernate,则只需在依赖项中包含org.hibernate:hibernate-java8

或者,如果您只想使用 JPA,则需要创建一个属性转换器。例如:

@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());
    }
}

属性转换器将处理Java LocalDate和MySQL Date之间的转换。

请参阅:http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/

最新更新