如何防止创建空对象

时间:2018-12-05 08:39:33

标签: mapstruct

我正在尝试将每个List都嵌套在嵌套对象中的网络服务模型映射到更简单的东西。

  1. 模型1
public class Parent {
   private Children children;
}

public class Children {
   private List<Child> children;
}

public class Child {
}
  1. 模型2(简体)
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对象。有什么办法可以防止这种情况?

1 个答案:

答案 0 :(得分:2)

您可以使用mapper decoratorAfterMapping 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);
        }
    }
}