spring boot、jackson 和 localdate
spring boot, jackson and localdate
我使用 spring 引导 mysql
在我的 application.properties
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'
在我的javaclass
进口java.time.LocalDate;
@Entity
public class WebSite implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long webSiteId;
private LocalDate date;
...
}
创建此 table 时,
日期字段的创建类似于 TINYBLOB
为什么不是日期
这不是 Jackson 的问题,而是您用于 ORM 的任何内容都不知道如何将 Java LocalDate 转换为 MySQL 日期。
有两种方法可以做到这一点。如果您使用的是 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 日期之间的转换。
参见:http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/
我使用 spring 引导 mysql
在我的 application.properties
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'
在我的javaclass
进口java.time.LocalDate;
@Entity
public class WebSite implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long webSiteId;
private LocalDate date;
...
}
创建此 table 时,
日期字段的创建类似于 TINYBLOB
为什么不是日期
这不是 Jackson 的问题,而是您用于 ORM 的任何内容都不知道如何将 Java LocalDate 转换为 MySQL 日期。
有两种方法可以做到这一点。如果您使用的是 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 日期之间的转换。
参见:http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/