![](/img/trans.png)
[英]How to map the source object of type String to target UUID in MapStruct?
[英]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
我有兩個對象源和目標,它們都具有相同的字段名稱和類型。
如果源字段是 null 我希望目標是“”(空字符串)
我的接口映射看起來像這樣(這只是兩個字段,我有很多)
@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)
如果源有一個值,它應該被復制,如果它在源中是 null,那么在目標中應該是“”。
Mapstruct-1.3.0 似乎只保留所有內容 null。
任何的想法? 我希望一切都默認為空字符串
您需要設置NullValuePropertyMappingStrategy
(作為Mapper
批注的一部分),以定義如何映射null屬性。
請參閱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);
}
當您的 Source object 具有與 Target object相同的字段並且當您想要管理所有 Source null值(例如對於 String)成為 Target object 中的空字符串(“”)時,您可以從MapStruct庫創建映射器接口,如下所示:
@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 文檔中閱讀更多相關信息。
因此,您必須在代碼中再執行一項操作並使用剛剛實現的“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 到空字符串的過程都在mapper.update(source, target)
方法下進行。 為您的項目運行mvn clean install
后,您可以在target/generated-sources/annotations/...../SourceToTargetMapperImpl.java
文件中檢查它的外觀和工作方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.