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>