![](/img/trans.png)
[英]Map multiple source fields to same type target fields with Mapstruct
[英]MapStruct map fields to target only when target's fields are null
我正在尝试映射此对象
public class Source {
private String value1;
private String value2;
private String value3;
}
进入这个对象
public class Target {
private String targetValue1;
private String targetValue2;
private String targetValue3;
}
这是映射器定义。
@Mapper
public interface SourceMapper {
void toTarget(Source source, @MappingTarget Target target);
}
我想要实现的是仅当target
中的字段为null
时才将source
的字段映射到target
。 例如, source.value1
仅在target.targetValue1
为null
时映射到target.targetValue1
。 如果它不是null
,则忽略该字段的映射。
是否可以使用 MapStruct 而无需编写自定义代码?
编辑我改变的字段名Target
,使之清楚,姓名Target
可能/可能不匹配的字段的名称Source
。
我认为这不能用 mapstruct 来完成。 如果您仍想使用 mapstruct,则可以使用@Mapping (target =" propName ", ignore = true)
可能为null的目标变量,并在设置目标变量时使用@AfterMapping
方法来决定自己。
您可以通过执行以下技巧来实现这一点:首先,您需要知道您可以使用Mapping.nullValuePropertyMappingStrategy()
控制“源”空字段上的映射行为,因此以下应该完成工作:
Target target = new Target(); // the actual target, first grade values
Source source = new Source(); // the actual source, secund grade values
Target result = new Target(); // the result
SourceMapper.toTarget(source, result); // now you have secund grade value
SourceMapper.toTarget(target, result); // now you overide the secund grade value only
if the first grade isn't null
@Mapper
public interface SourceMapper {
@Mapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
void toTarget(Target source, @MappingTarget Target target);
void toTarget(Source source, @MappingTarget Target target);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.