如果 属性 为空,如何让 MapStruct 不生成包装器对象?

How to have MapStruct not generate wrapper object if property is null?

我有一些代码使用 MapStruct 将 from.id 映射到 to.ref.id 结构。当 from.id 为 null 时,MapStruct 将创建一个新的 Reference 实例并将其 id 设置为 null。我如何让它不生成包装器 class,并将 to.ref 设置为空?

我已经为映射的 nullValueCheckStrategynullValuePropertyMappingStrategy 尝试了不同的值,但对于这种情况,这些值似乎没有任何区别。

这是我的代码,为简洁起见省略了 getter 和 setter。

public class Example {
    public static void main(String[] args) {
        System.out.println(Mappers.getMapper(MyMapper.class).get(new From()));
    }
}

@Mapper
interface MyMapper {
    @Mapping(source = "id", target = "ref.id")
    To get(From from);
}

class From {
    private String id;
}

class To {
    private Reference ref;
}

class Reference {
    private String id;
}

你可以试试这样的

创建一个新的映射器如下。

@Mapper
public interface Mapper1 {
    @Mapping(source = "id", target = "id")
    Reference get(String id);
}

然后更新您退出的映射器以像这样使用这个新的映射器

@Mapper(uses = Mapper1.class)
public interface MyMapper {

    @Mapping(source = "from.id", target = "ref")
    To get(From from);
}