如何使用 modelMapper 转换嵌套类

2022-09-02 10:27:31

我有一个简单的类,我想使用模型映射器映射到DTO类。

class Source {

    private String name;
    private String address;
    List<Thing> things;

    // getters and setters follows
    }

    class Thing {

    private String thingCode;
    private String thingDescription;

    // getters and setters
}

并且我想将它们转换为包含ThingDTO列表的sourceDTO,例如

class sourceDTO {

    private String name;
    private String address;
    List<ThingDTO> things;

    // getters and setters.
    }

     class ThingDTO {

    private String thingCode;
    private String thingDescription;

    // getters and setters
}

如果我放下我的事物列表和事物DTO列表,那么模型映射器是一种乐趣,

 modelMapper.map(source, SourceDTO.class);

但是我无法弄清楚如何让映射器将事物列表转换为ThingDTO列表。从文档中,我认为我需要创建一个扩展 PropertyMap 的映射器类,但我无法确定如何配置它。

欢迎任何指向相关文档的指针


答案 1

我认为,如果您将模型映射器配置为松散或标准,它将为您服务。

modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);

其他你接下来可以尝试:

  1. 您可以创建一个转换器,例如:

    public class ListThingToThingDTOConverter implements Converter<List<Thing>, List<ThingDTO>> {
    
    
    @Override
    public List<ThingDTO> convert(MappingContext<List<Thing>, List<ThingDTO>> context) {
        List<Thing> source = context.getSource();
        List<ThingDTO> output = new ArrayList<>();
        ...
        //Convert programmatically List<Thing> to List<ThingDTO>
        ...
    
        return output;
      }}
    
  2. 然后自定义将事物映射到事物DTO,如下所示:

        public class SourceToSourceDTOMap extends PropertyMap<Thing, ThingDTO> {
              @Override
              protected void configure(){
                   using(new ListThingToThingDTOConverter()).map(source.getThings()).setThings(null);
              }
    
  3. 最后,您必须将SourceToSourceDTOMap添加到您的模型映射器中,如下所示:

    modelMapper = new ModelMapper();
    modelMapper.addMappings(new SourceToSourceDTOMap());
    

答案 2

您可以通过创建泛型来像下面的代码一样进行映射。链接以供参考

http://modelmapper.org/user-manual/generics/

进口:

import java.lang.reflect.Type;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;

在服务或控制器类中:

ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<SourceDTO>(){}.getType();
SourceDTO sourceDTO = modelMapper.map(source,listType);

推荐