2017-04-13 1175 views
0

我想如果所有屬性在@映射/源引用都爲空所生成的mapstruct映射方法返回null。 對於爲例,我有以下映射:Mapstruct映射:如果所有源參數屬性爲null返回null對象

@Mappings({ 
     @Mapping(target = "id", source = "tagRecord.tagId"), 
     @Mapping(target = "label", source = "tagRecord.tagLabel") 
}) 
Tag mapToBean(TagRecord tagRecord); 

生成的方法則是:

public Tag mapToBean(TagRecord tagRecord) { 
    if (tagRecord == null) { 
     return null; 
    } 

    Tag tag_ = new Tag(); 

    if (tagRecord.getTagId() != null) { 
     tag_.setId(tagRecord.getTagId()); 
    } 
    if (tagRecord.getTagLabel() != null) { 
     tag_.setLabel(tagRecord.getTagLabel()); 
    } 

    return tag_; 
} 

測試用例:TagRecord對象不爲空,但有TAGID == null並且tagLibelle == NULL。

當前行爲:返回Tag對象不爲空,但標籤識別== null並且tagLibelle == NULL

什麼其實我是想生成的方法做的是返回一個空標籤對象,如果(tagRecord.getTagId ()== NULL & & tagRecord.getTagLabel()== NULL)。 這是可能的嗎?我該如何做到這一點?

回答

1

目前這不是從MapStruct直接支持。然而,你可以達到你想要的東西的Decorators的幫助下,你將不得不手動檢查所有的字段爲空,並返回null而不是對象。

@Mapper 
@DecoratedWith(TagMapperDecorator.class) 
public interface TagMapper { 
    @Mappings({ 
     @Mapping(target = "id", source = "tagId"), 
     @Mapping(target = "label", source = "tagLabel") 
    }) 
    Tag mapToBean(TagRecord tagRecord); 
} 


public abstract class TagMapperDecorator implements TagMapper { 

    private final TagMapper delegate; 

    public TagMapperDecorator(TagMapper delegate) { 
     this.delegate = delegate; 
    } 

    @Override 
    public Tag mapToBean(TagRecord tagRecord) { 
     Tag tag = delegate.mapToBean(tagRecord); 

     if (tag != null && tag.getId() == null && tag.getLabel() == null) { 
      return null; 
     } else { 
      return tag; 
     } 
    } 
} 

我寫(構造)的例子是用於與該default組件模型映射器。如果你需要使用Spring或不同DI框架來看看: