2 回答

TA貢獻1860條經驗 獲得超9個贊
您需要設置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);
}

TA貢獻1805條經驗 獲得超9個贊
當您的 Source 對象具有與 Target 對象相同的字段并且當您想要管理所有 Source空值(例如對于 String)成為Target 對象中的空字符串(“”)時,您可以從MapStruct庫創建映射器接口,如下所示:
步驟1:
@Mapper(componentModel = "spring")
public interface SourceToTargetMapper {
? Target map(Source source);
? @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT)
? void update(Source source, @MappingTarget Target target);
}
整個技巧是定義nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT,但您不能在 @Mapper 注釋中定義它。取而代之的是,您必須將它作為參數放在update()方法的 @BeanMapping 注釋中。您可以在MapStruct 文檔中閱讀更多相關信息。
第2步:
因此,您必須在代碼中再執行一項操作并使用剛剛實現的“update()”方法:
@Component
public class ClassThatUsingMapper {
? private final SourceToTargetMapper mapper;
? public Target someMethodToMapObjects(Source source) {
? ? Target target = mapper.map(source);
? ? mapper.update(source, target)
? ? return target;
? }
}
所有null 到空 String 的過程都發生在mapper.update(source, target)method 下。為您的項目運行后mvn clean install,您可以檢查它的外觀以及它在target/generated-sources/annotations/...../SourceToTargetMapperImpl.java文件中的工作方式。
添加回答
舉報