如何防止创建空对象

2024-03-29

我正在尝试将每个列表都位于嵌套对象内部的网络服务模型映射到更简单的东西。

  1. Model 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 对象。有什么办法可以防止这种情况发生吗?


您可以通过以下方式实现这一目标映射器装饰器 http://mapstruct.org/documentation/stable/reference/html/#customizing-mappers-using-decorators or an AfterMapping 钩子 http://mapstruct.org/documentation/stable/reference/html/#customizing-mappings-with-before-and-after.

装饰者

装饰者:

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;
    }
}

Mapper:

@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);
}

映射后

Mapper:

@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);
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何防止创建空对象 的相关文章

随机推荐