【问题标题】:java modelMapper: Mapping a Collection to an Objectjava modelMapper:将集合映射到对象
【发布时间】:2018-12-14 01:31:20
【问题描述】:

在对该主题进行大量测试和研究后,我无法完全解决我的问题。我在 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 的一些东西。

最好的问候,

【问题讨论】:

    标签: java spring spring-boot modelmapper


    【解决方案1】:

    我没有使用过 ModelMapper,但是docs 建议你可以使用 TypeToken

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

    【讨论】:

    • 感谢您的回答。它适用于文档中描述的“直接”映射,但我无法使用该解决方案设置“全局转换器”(每次发生 Set 和对象之间的映射时都会执行的转换器)。
    • 如果我使用token,转换器与typeMap不匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多