我正在结合Lombok和构建器模式使用MapSTRt。我有一个问题,即MapSTRt正在对生成的映射器函数中的所有参数进行显式空检查,并在所有参数为空的情况下提前退出,例如:
// Object A
@Value
@Builder(builderClassName = "Builder")
public class SourceA{
private int a;
}
// Object B
@Value
@Builder(builderClassName = "Builder")
public class SourceB{
private int a;
}
// Object C
@Value
@Builder(builderClassName = "Builder")
public class SourceC{
private int a;
}
// Object Target
@Value
@Builder(builderClassName = "Builder")
public class Target{
private int a;
private int b;
private int c;
}
// Mapper
@Mapper(componentModel = "spring")
public interface Mapper {
@Mappings({
@Mapping(target = "a", source = "sourceA.a"),
@Mapping(target = "b", source = "sourceB.a"),
@Mapping(target = "c", source = "sourceC.a")
})
Target toTarget(SourceA sourceA, SourceB sourceB, SourceC sourceC);
};
// mapstruct impl
// Auto Generated by MapStruct!
public class MapperImpl implements Mapper {
public Target toTarget(SourceA sourceA, SourceB sourceB, SourceC sourceC){
// Problamatic line
if (sourceA == null && sourceB == null && sourceC == null) {
return null;
} else {
Target.Builder builder = Target.builder();
// map objects
return builder.builder();
}
}
}
我想实现MapStruct不实现完整的空检查。即使所有参数都为null,它也应该设置整个生成器,并在生成器进行null检查(如果有)时调用build。
为了实现所需的目标,请始终使用NullValueMappingStrategy
创建目标对象的默认实例。
在mapper上,您可以执行@mapper(nullValueMappingStrategy=nullValueMappingStrategy.RETURN_DEFAULT)
当您执行此操作时,生成的代码应该如下所示:
public class MapperImpl implements Mapper {
public Target toTarget(SourceA sourceA, SourceB sourceB, SourceC sourceC){
Target.Builder builder = Target.builder();
// map objects
return builder.builder();
}
}