Как предотвратить создание пустых объектов - PullRequest
0 голосов
/ 05 декабря 2018

Я пытаюсь сопоставить модель веб-сервиса, где каждый List находится внутри вложенного объекта, с чем-то более простым.

  1. Модель 1
public class Parent {
   private Children children;
}

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

public class Child {
}
Модель 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 голосов
/ 10 декабря 2018

Этого можно добиться как с помощью mapper decorator , так и AfterMapping hook .

Decorator

Decorator:

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

AfterMapping

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