2019独角兽企业重金招聘Python工程师标准>>>
Spring boot项目,使用dozer将Jpa Entity中的LocalDateTime属性转到DTO中对应的LocalDateTime属性中报错
java.lang.NoSuchMethodException: java.time.LocalDateTime.()
at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_51]
at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_51]
at org.dozer.factory.ConstructionStrategies$ByConstructor.newInstance(ConstructionStrategies.java:272) ~[dozer-5.5.1.jar:na]
将DTO中的LocalDateTime换成Date又报错
java.lang.NumberFormatException: For input string: "2015-10-17T17:55:12.091"
解决方法:
添加一个自定义Convert
public class LocalDateTimeToDateDozerConverter extends DozerConverter {
public LocalDateTimeToDateDozerConverter() {
super(LocalDateTime.class, Date.class);
}
@Override
public LocalDateTime convertFrom(Date source, LocalDateTime destination) {
LocalDateTime dateTime = LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
return dateTime;
}
@Override
public Date convertTo(LocalDateTime source, Date destination) {
Date convertToDate = Date.from(source.atZone(ZoneId.systemDefault()).toInstant());
return convertToDate;
}
}
在类路径下添加一个xml配置文件
java.time.LocalDateTime
java.util.Date
注意像这样的全局配置只能使用xml的形式配置,见官方文档
In fact some parts of the configuration (e.g. global configuration block) are only possible to express in Xml format.
Spring boot启动类中添加如下配置
@Bean
public Mapper dozerBeanMapper() {
List mappingFileUrls = Lists.newArrayList("dozer-custom-convert.xml");
DozerBeanMapper mapper = getSingletonDozerBeanMapper();
mapper.setMappingFiles(mappingFileUrls);
return mapper;
}
参考文档
http://dozer.sourceforge.net/documentation/customconverter.html
http://stackoverflow.com/questions/29550417/why-dozerconverter-is-not-working