2017-04-13 1184 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框架来看看: