我有一些代码使用MapStruct将from.id
映射到to.ref.id
结构。当from.id
为空时,MapStruct将创建一个新的Reference
实例并将其id
设置为null
。我该如何使其不生成包装器类,并将to.ref
设置为null?
我为映射的nullValueCheckStrategy
和nullValuePropertyMappingStrategy
尝试了不同的值,但是在这种情况下,这些值似乎没有什么区别。
这是我的代码,为简洁起见,省略了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;
}
答案 0 :(得分:2)
您可以尝试这样的事情
按如下所示创建一个新的映射器。
@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);
}