我正在尝试将每个List都嵌套在嵌套对象中的网络服务模型映射到更简单的东西。
public class Parent { private Children children; } public class Children { private List<Child> children; } public class Child { }
public class Parent2 { private List<Child2> children; } public class Child { }
映射非常简单:
@Mappings({@Mapping(source = "entity.children.children", target = "children")}) Parent2 parentToParent2(Parent entity); @InheritInverseConfiguration Parent parent2ToParent(Parent2 entity);
除一个问题外,映射工作正常。当我将具有空子级的Parent映射到Parent2并返回到Parent时,将创建带有空列表的Children对象。有什么办法可以防止这种情况?
答案 0 :(得分:2)
您可以使用mapper decorator或AfterMapping hook来实现。
装饰器:
public abstract class MapperDecorator implements Mapper {
private final Mapper delegate;
public MapperDecorator(Mapper delegate) {
this.delegate = delegate;
}
@Override
public Parent parent2ToParent(Parent2 entity) {
Parent parent = delegate.parent2ToParent(entity);
if (entity.getChildren() == null) {
parent.setChildren(null);
}
return parent;
}
}
映射器:
@org.mapstruct.Mapper
@DecoratedWith(MapperDecorator.class)
public interface Mapper {
@Mapping(source = "entity.children.children", target = "children")
Parent2 parentToParent2(Parent entity);
@InheritInverseConfiguration
Parent parent2ToParent(Parent2 entity);
Child2 childToChild2(Child entity);
Child child2ToChild(Child2 entity);
}
映射器:
@org.mapstruct.Mapper
public abstract class Mapper {
@Mapping(source = "entity.children.children", target = "children")
public abstract Parent2 parentToParent2(Parent entity);
@InheritInverseConfiguration
public abstract Parent parent2ToParent(Parent2 entity);
public abstract Child2 childToChild2(Child entity);
public abstract Child child2ToChild(Child2 entity);
@AfterMapping
public void afterParent2ToParent(Parent2 source,
@MappingTarget Parent target) {
if (source.getChildren() == null) {
target.setChildren(null);
}
}
}