如何映射一个对象包含其他对象

How to Map an object contains other object

鉴于来源 class 定义如下:

class Source{
    private String name;
    private int age;
    Phone phone
    // getters and setters
}

和 Phone class 定义如下:

class Phone{
        private Long id;
        private String phoneNumber;
        // getters and setters
    }

和目标 class 定义如下:

class Target{
    private String name;
    private int age;
    private Long phone;
    // getters and setters
}

我有一个接口:

@Mapper
interface MyMapper{
    @Mapping(source = "phone.id", target = "phone")
    Target toTarget(Source source);
    @Mapping(source = "phone", target = "phone.id")
    Source toSource(Target target);
}

如何更改生成的代码以在 id 为 null 时消除 Phone 对象,

生成代码;

source.setPhone(target t){
  if(t==null){
     return null;
  }
Phone f=new Phone();
if(t.getPhone!=null){
    f.setId(t.getPhone();
}
return f;
//in this case mapstruct create an object, even if the source is null
}

这在 MapStruct 中目前是不可能的。已经有一个类似这样的功能请求(参见 #1166)。

实现此目的的唯一方法是使用 @AfterMapping 并将您的 phone 设置为 null 如果 ID 为 null

您可以通过以下方式使用@AfterMapping

@Mapper
public interface MyMapper {

    Source map(Target target);

    @AfterMapping
    void afterMapping(@MappingTarget Source source) {
        if (source.getPhone() != null && source.getPhone().getId() == null) {
            source.setPhone(null);
        }
    }
}