Dozer 自定义Converter -- LocalDateTime to Date

Spring boot项目,使用dozer将Jpa Entity中的LocalDateTime属性转到DTO中对应的LocalDateTime属性中报错

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.lang.NumberFormatException: For input string: "2015-10-17T17:55:12.091"

解决方法:

添加一个自定义Convert

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配置文件

<?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的形式配置,见官方文档

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<String> 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


你可能感兴趣的:(Dozer)