Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mapstruct

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.

like image 489
Phuong Hoang Avatar asked Aug 03 '26 16:08

Phuong Hoang


1 Answers

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.

like image 55
Malsor Avatar answered Aug 05 '26 06:08

Malsor