Spring boot項目,使用dozer將Jpa Entity中的LocalDateTime屬性轉到DTO中對應的LocalDateTime屬性中報錯html
java.lang.NoSuchMethodException: java.time.LocalDateTime.<init>() 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
java.lang.NumberFormatException: For input string: "2015-10-17T17:55:12.091"
解決方法:express
添加一個自定義Convertapi
public class LocalDateTimeToDateDozerConverter extends DozerConverter<LocalDateTime, Date> { 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配置文件app
<?xml version="1.0" encoding="UTF-8"?> <mappings xmlns="http://dozer.sourceforge.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://dozer.sourceforge.net http://dozer.sourceforge.net/schema/beanmapping.xsd"> <configuration> <custom-converters> <!-- these are always bi-directional --> <converter type="com.demo.LocalDateTimeToDateDozerConverter" > <class-a>java.time.LocalDateTime</class-a> <class-b>java.util.Date</class-b> </converter> </custom-converters> </configuration> </mappings>
注意像這樣的全局配置只能使用xml的形式配置,見官方文檔ide
In fact some parts of the configuration (e.g. global configuration block) are only possible to express in Xml format.spa
Spring boot啓動類中添加以下配置.net
@Bean public Mapper dozerBeanMapper() { List<String> mappingFileUrls = Lists.newArrayList("dozer-custom-convert.xml"); DozerBeanMapper mapper = getSingletonDozerBeanMapper(); mapper.setMappingFiles(mappingFileUrls); return mapper; }
參考文檔code
http://dozer.sourceforge.net/documentation/customconverter.html orm
http://stackoverflow.com/questions/29550417/why-dozerconverter-is-not-working