Max*_*Max 4 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);
Run Code Online (Sandbox Code Playgroud)
生成的方法是:
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_;
}
Run Code Online (Sandbox Code Playgroud)
测试用例:TagRecord 对象不为空,但具有 tagId==null 和 tagLibelle==null。
当前行为:返回的 Tag 对象不为 null,但具有 tagId==null 和 tagLibelle==null
如果(tagRecord.getTagId() == null && tagRecord.getTagLabel() == null),我实际上希望生成的方法做的是返回一个空标签对象。有可能吗,我怎样才能做到这一点?
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我编写的示例(构造函数)适用于具有default组件模型的映射器。如果您需要使用 Spring 或其他 DI 框架,请查看:
@DecoratedWith,但你应该使用CDI装饰代替| 归档时间: |
|
| 查看次数: |
6269 次 |
| 最近记录: |