'Map nullable to several properties and specify default value for each

I try to map an enum (may be null) to a bean with 2 properties. There is a mapping from the (source) enum to either properties and I have a default value for either property in the case the (source) enum is null. However, in the generated mapping code the default values per property are never used as the initial null check immediately returns a null (result) bean. The code example might help to understand the issue. S is the source enum, R is the expected result (bean) with the two properties t1 of type T1 and t2 of type T2. This is my mapper with S, T1, T2, R inline for easier trying out:

@Mapper
public interface MyMapper {
  static enum S {A, B, C, D}
  static enum T1 {A, B, C, D}
  static enum T2 {X, Y}
  @Data
  @Builder
  static class R {
    private T1 t1;
    private T2 t2;
  }

  @Mapping(source = "source", target = "t1", defaultValue = "A")
  @Mapping(source = "source", target = "t2", defaultValue = "X")
  R sToR(S source);

  @ValueMapping(source = "A", target = "X")
  @ValueMapping(source = "B", target = "X")
  @ValueMapping(source = "C", target = "Y")
  @ValueMapping(source = "D", target = "Y")
  T2 sToT2(S source);
}

The generated code of sToR looks like this:

@Override
public R sToR(S source) {
    if ( source == null ) {
        return null;
    }

    RBuilder r = R.builder();

    if ( source != null ) {
        r.t1( sToT1( source ) );
    }
    else {
        r.t1( T1.A );
    }
    if ( source != null ) {
        r.t2( sToT2( source ) );
    }
    else {
        r.t2( T2.X );
    }

    return r.build();
}

Everything would be as expected, if I just could get rid of the initial if(source==null){return null;} but so far I failed.



Solution 1:[1]

There is an open issue (mapstruct/mapstruct#1243) for MapStruct to work with Nullable, NotNull etc.

Until that one is resolved there isn't much that MapStruct can do in the moment and you will have to live with the null check

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Filip