【问题标题】:Mapping List of Object From Parent Object which has a List of Objects从具有对象列表的父对象映射对象列表
【发布时间】:2018-12-02 11:35:41
【问题描述】:

我正在尝试使用 mapstruct 来转换对象,如下所示

来源

MainObject
{

    String key;
    List<ChildObject> children;
}

ChildObject{

    String childVar1;
    String childVar2;

}

目标

List<TargetObj> targetObjects;

TargetObj{

    String key;
    String var1;
    String var2;

}

我需要准备一个 TargetObj 实例列表,其中的键映射自 MainObject 的键以及映射自 ChildObject 的 var1 和 var2。 我尝试使用 mapstruct 文档中提到的 ObjectFactory 和 Decorator。但是找不到完成这项工作的方法。这两种情况我都得到了一个错误,指出不能从不可迭代的参数返回可迭代对象。

【问题讨论】:

    标签: java-8 mapstruct


    【解决方案1】:

    您可以尝试将@BeforeMapping@AfterMapping@Context 结合使用。

    您的映射器可能如下所示:

    @Mapper
    public interface MyMapper {
    
        default List<TargetObj> map(MainObject source) {
            if (source == null) {
                return Collections.emptyList(); // or null or whatever you prefer 
            }
            return map(source.getChildren(), new CustomContext(source));
        }
    
        List<TargetObject> map(List<ChildObject> children, @Context CustomContext context);
    
        @Mapping(target = "key", ignore = true) // key is mapped in the context
        TargetObject map(ChildObject child, @Context CustomContext context);
    }
    

    自定义上下文看起来像:

    public class CustomContext {
    
        protected final MainObject mainObject;
    
        public CustomContext(MainObject mainObject) {
            this.mainObject = mainObject;
        }
    
        @AfterMapping // of @BeforeMapping
        public void afterChild(@MappingTarget ChildObject child) {
            child.setKey(mainObject.getKey());
            // More complex mappings if needed
        }
    }
    

    目标是通过使用 MapStruct 将生成的其他方法从您的 MainObject 手动映射到 List&lt;TargetObj&gt;

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      相关资源
      最近更新 更多