如果 @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)。
这可能吗?我怎样才能实现这一目标?
目前 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 框架,请查看:
- Spring 装饰器
- 使用 JSR 330 的装饰器
- 如果您使用 CDI,那么您不应该使用
@DecoratedWith
,但你应该使用CDI 装饰器 instead
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)