Mapstruct 映射:Return 如果所有源参数属性都为空,则为空对象

Mapstruct Mapping : Return null object if all source parameters properties are null

如果@Mapping/source中引用的所有属性都为null,我希望生成的mapstruct映射方法为returnnull。 例如,我有以下映射:

@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。

当前行为:returned Tag 对象不为空,但有 tagId==null 和 tagLibelle==null

我实际上想要生成的方法做的是 return 一个空标签对象 if (tagRecord.getTagId() == null && tagRecord.getTagLabel() == null)。 这可能吗?我该如何实现?

MapStruct 目前不直接支持此功能。但是,您可以在 Decorators 的帮助下实现您想要的,并且您必须手动检查是否所有字段都为空并且 return 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 框架,请查看: