ma.glasnost.orika.MappingException:No converter registered for conversion from Date to LocalDateTime

背景

  • 背景orika api转换成另一个类型的List对象,字段从Date转为LocalDateTime报错。
  • 详细异常
ma.glasnost.orika.MappingException: No converter registered for conversion from Date to LocalDateTime, nor any ObjectFactory which can generate LocalDateTime from Date
        at ma.glasnost.orika.impl.DefaultMapperFactory.lookupMapper(DefaultMapperFactory.java:726)
        at ma.glasnost.orika.impl.MapperFacadeImpl.resolveMapper(MapperFacadeImpl.java:568)
        at ma.glasnost.orika.impl.MapperFacadeImpl.resolveMappingStrategy(MapperFacadeImpl.java:178)
        at ma.glasnost.orika.impl.DefaultBoundMapperFacade$BoundStrategyCache.getStrategy(DefaultBoundMapperFacade.java:259)
        at ma.glasnost.orika.impl.DefaultBoundMapperFacade.map(DefaultBoundMapperFacade.java:137)
        ......

解决方案

  • 增加转换器。

import cn.hutool.core.date.DateUtil;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ma.glasnost.orika.metadata.Type;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author Zhou Zhongqing
 * @description: 向Spring注册对象复制的全局对象
 * @date 2022/5/20 14:20
 */
@Configuration
public class OrikaMapperFactoryConfig {
    @Bean
    public MapperFactory mapperFactory() {
        return new DefaultMapperFactory.Builder().build();
    }

    @Bean
    public MapperFacade mapperFacade() {
        MapperFactory mapperFactory = mapperFactory();
        // Date 和LocalDateTime 的相互转换
        mapperFactory.getConverterFactory().registerConverter(new OrikaDateConverter());
        return mapperFactory.getMapperFacade();
    }

    /**
     * Date 和LocalDateTime 的相互转换
     */
    public class OrikaDateConverter extends BidirectionalConverter<Date, LocalDateTime> {


        @Override
        public LocalDateTime convertTo(Date source, Type<LocalDateTime> destinationType, MappingContext mappingContext) {
            return DateUtil.toLocalDateTime(source);
        }

        @Override
        public Date convertFrom(LocalDateTime source, Type<Date> destinationType, MappingContext mappingContext) {
            String format = "yyyy-MM-dd HH:mm:ss";
            String str = DateUtil.format(source, "yyyy-MM-dd HH:mm:ss");
            return DateUtil.parse(str, format);
        }

    }


}

DateUtil使用的是hutool的。

  • 当遇上Date类型转为LocalDateTime会进入OrikaDateConverter#convertTo方法。如下图所示。

convertFrom方法是Date类型转LocalDateTime时会用到

在这里插入图片描述

  • 这样就能转换成功了。

posted on 2022-08-28 11:26  愤怒的苹果ext  阅读(305)  评论(0编辑  收藏  举报

导航