简体   繁体   中英

MapStruct map fields to target only when target's fields are null

I am trying to map this object

public class Source {
  private String value1;
  private String value2;
  private String value3;
}

Into this object

public class Target {
  private String targetValue1;
  private String targetValue2;
  private String targetValue3;
}

This is the Mapper definition.

@Mapper
public interface SourceMapper {
  void toTarget(Source source, @MappingTarget Target target);
}

What I am trying to achieve is only map fields in source into target only when the fields in target are null . For example, source.value1 only maps to target.targetValue1 when target.targetValue1 is null . If it is not null , the mapping for that field is ignored.

Is it possible with MapStruct without having to write custom code?

Edit I changed the field names of Target to make it clear that the names of the Target may/may not match the names of the fields in Source .

I don't think that can be done with mapstruct. If you still want to use mapstruct, you can ignore the target variables that could be null with @Mapping (target =" propName ", ignore = true) and decide yourself with a @AfterMapping method when you set your target variables.

You can achieve that by doing the following trick: first, you need to know that you can control the mapping behavior on 'source' nulls fields using Mapping.nullValuePropertyMappingStrategy() So the following should do the work:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM