Mapstruct Mapping:如果所有源参数属性为null,则返回null对象

时间:2017-04-13 12:11:16

标签: java object-object-mapping mapstruct

如果@ Mapping / source中引用的所有属性都为null,我希望生成的mapstruct映射方法返回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对象不为null,但tagId == null,tagLibelle == null。

当前行为:返回的Tag对象不为null,但是tagId == null和tagLibelle == null

我真正想要生成的方法是返回一个null Tag对象if(tagRecord.getTagId()== null&& tagRecord.getTagLabel()== null)。 是否可能,我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

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框架,请查看:

相关问题