如何使用modelMapper转换嵌套类

use*_*087 9 java modelmapper

我有一个简单的类,我想使用modelMapper映射到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
}
Run Code Online (Sandbox Code Playgroud)

我想将这些转换为包含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
}
Run Code Online (Sandbox Code Playgroud)

如果我删除我的物品列表和ThingsDTO列表,那么modelmapper是一个令人愉快的使用,

 modelMapper.map(source, SourceDTO.class);
Run Code Online (Sandbox Code Playgroud)

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

欢迎提供相关文档的任何指示

Pau*_*Pau 9

我认为如果你将ModelMapper配置为LOOSE或STANDARD它会为你做.

modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
Run Code Online (Sandbox Code Playgroud)

其他你可以尝试下一个:

  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;
      }}
    
    Run Code Online (Sandbox Code Playgroud)
  2. 然后自定义一个映射到ThingDTO的东西:

        public class SourceToSourceDTOMap extends PropertyMap<Thing, ThingDTO> {
              @Override
              protected void configure(){
                   using(new ListThingToThingDTOConverter()).map(source.getThings()).setThings(null);
              }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 最后,您必须将SourceToSourceDTOMap添加到ModelMapper中,如下所示:

    modelMapper = new ModelMapper();
    modelMapper.addMappings(new SourceToSourceDTOMap());
    
    Run Code Online (Sandbox Code Playgroud)

  • 这次真是万分感谢。我不知道为什么这在很多地方都没有得到很好的解释。这就像基本要求,必须进行大量搜索才能找到解决方案。感谢您的回答。节省大量时间。 (2认同)