当前位置: 首页 > 知识库问答 >
问题:

从具有对象列表的父对象映射对象列表

唐阳飇
2023-03-14
MainObject
{

    String key;
    List<ChildObject> children;
}

ChildObject{

    String childVar1;
    String childVar2;

}
List<TargetObj> targetObjects;

TargetObj{

    String key;
    String var1;
    String var2;

}

共有1个答案

苏高峰
2023-03-14

您可以尝试将@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
    }
}
 类似资料: