Mapstruct:当源为空时如何将目标字符串默认为空字符串(两个字段具有相同的名称和类型)Java / Spring

Mapstruct: How to default a target String to Empty String when the Source is Null (Both fields have the same name and type) Java / Spring

我有两个对象源和目标,它们都具有相同的字段名称和类型。

如果源字段为空,我希望目标为“”(空字符串)

我的接口映射是这样的(这只是两个字段,我有很多)

@Mapper(componentModel = "spring", nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
public interface MyMapper {

@Mappings({
    @Mapping(target="medium", defaultExpression="java(\"\")"),
    @Mapping(target="origin", defaultExpression="java(\"\")")
 }) 
public Target mapFrom(Source source)

如果 Source 有一个值,它应该被复制过来,如果它在源中为 null,那么它在目标中应该是 ""。

Mapstruct-1.3.0 似乎只保留所有内容。

有什么想法吗?我希望一切都默认为空字符串

您需要设置 NullValuePropertyMappingStrategy(作为 Mapper 注释的一部分)以定义空属性的映射方式。

NullValuePropertyMappingStrategy.html#SET_TO_DEFAULT

String 的默认值为 ""。您不需要明确定义它。

因此,您的映射器可以简单地如下所示:

@Mapper(
    componentModel = "spring", 
    nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT, 
    nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT
)
public interface MyMapper {

    public Target mapFrom(Source source);

}