• JPA 添加 converter


    JPA 添加 converter

    1. 问题描述

    No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type xxx
    

    DTO, JPA 查询返回的结果是 List<Map<String, Object>>, 需要添加自定义的 Converter 进行类型转换。

    2. 解决方案

    通过添加注解,在程序启动时自动添加相关类的的 Converter

    @Documented
    @Component
    @Target(value = {ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface JpaDtoConverter{
    
    }
    
    @Slf4j
    @Configuration
    public class DtoJpaConfiguration {
        @Autowired
        private ApplicationContext applicationContext;
    
        /**
         * 初始化注入@JpaDto对应的Converter
         */
        @PostConstruct
        public void init() {
            Map<String, Object> map = applicationContext.getBeansWithAnnotation(JpaDtoConverter.class);
            for (Object o : map.values()) {
                Class c = o.getClass();
                log.info("Jpa添加Converter,class={}", c.getName());
                GenericConversionService genericConversionService = ((GenericConversionService) DefaultConversionService.getSharedInstance());
                genericConversionService.addConverter(Map.class, c, m -> {
                    try {
                        Object obj = c.newInstance();
                        return map2Pojo(m, obj.getClass());
                    } catch (Exception e) {
                        throw new FatalBeanException("Jpa结果转换出错,class=" + c.getName(), e);
                    }
                });
            }
        }
    
        public static <T> T map2Pojo(Object entity, Class<T> tClass) {
            CopyOptions copyOptions = CopyOptions.create()
                    .setIgnoreCase(true)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true)
                    .setFieldNameEditor(StrUtil::toUnderlineCase);
            return BeanUtil.toBean(entity, tClass, copyOptions);
        }
    }
    

    3. 使用注解

    @JpaDtoConverter
    @Data
    public class Xxx {
        @ApiModelProperty(value = "xxx")
        private int xxx;
    }
    

    注: 需要引入 hutool 包

    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.5.5</version>
    </dependency>
  • 相关阅读:
    Python深入05 装饰器
    Python深入04 闭包
    Python深入03 对象的属性
    Ubuntu (虚拟机同样) 更换内核?
    .out
    GCC 编译详解
    linux 编译内核 /boot空间不足?
    Java Swing提供的文件选择对话框
    Java Swing 实时刷新JTextArea,以显示不断append的内容?
    为什么要编译Linux内核?
  • 原文地址:https://www.cnblogs.com/54hys/p/15816857.html
Copyright © 2020-2023  润新知