簡體   English   中英

Mapstruct:當源為 Null 時如何將目標字符串默認為空字符串(兩個字段具有相同的名稱和類型)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

我有兩個對象源和目標,它們都具有相同的字段名稱和類型。

如果源字段是 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庫創建映射器接口,如下所示:

步驟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 到空字符串的過程都在mapper.update(source, target)方法下進行。 為您的項目運行mvn clean install后,您可以在target/generated-sources/annotations/...../SourceToTargetMapperImpl.java文件中檢查它的外觀和工作方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM