首页 > 解决方案 > java modelMapper:将集合映射到对象

问题描述

经过对这个主题的大量测试和研究,我无法完全解决我的问题。我在 springboot 应用程序中使用 modelmapper 进行实体/DTO 映射。我正在尝试配置我的模型映射器以将 Set 映射到一个简单的 DTO 对象。我已经创建了一个自定义转换器,它按预期工作:

Converter<Set<CategoryTl>, CategoryTlDTO> converter = new AbstractCustomConverter<Set<CategoryTl>, CategoryTlDTO>() {
        @Override
        protected D convert(S source, MappingContext<Set<CategoryTl>, CategoryTlDTO> context) {
            HashMap<String, CategoryTlDetailsDTO> map = new HashMap<>();

             source.forEach(
                    categoryTl -> map.put(categoryTl.getCatalogLanguage().getLanguage().getCode(),
                            new CategoryTlDetailsDTO(categoryTl.getName(), categoryTl.getDescription()))
            );

           return new CategoryTlDTO(map);
        }
    };

我现在的问题是将此转换器应用于所有“Set => CategoryTlDTO”。是否在嵌套对象中。我尝试创建一个新的 TypeMap,但由于“Set”集合而无法创建。

mapper.createTypeMap(Set<CategoryTl>.class (-> not possible), CategoryTlDTO.class).setConverter(converter);

如果我直接在模型映射器中添加转换器,它就不起作用。

mapper.addConverter(converter);

您对此有任何提示或解决方案吗?也许我错过了关于 TypeToken 和 TypeMap Inheritance 的一些东西。

此致,

标签: javaspringspring-bootmodelmapper

解决方案


我没有使用过 ModelMapper,但文档建议您可以使用 TypeToken

Type setType = new TypeToken<Set<CategoryTl>>() {}.getType();
mapper.createTypeMap(setType, CategoryTlDTO.class).setConverter(converter);

推荐阅读