javamapstruct

Ignore Null check at source , while Mapping methods with several source parameters


Team, I have a use case related to map struct . PFB my interface

@Mappings({
    @Mapping(source = "source1.name", target = "name"),
    @Mapping(source = "source2.address", target = "address"),
    @Mapping(source = "source3.company", target = "company")
})
public SomeClass map(Source1 source1,Source2  source2,Source3 source3);

Everything works fine. But my issue is with the below snippet(which is generated by the mapstruct based on the above defined interface)

public SomeClass map(Source1 source1,Source2  source2,Source3 source3)(
        if ( source1== null && source2== null && source3== null ) {
            return null;
        }

Here My issue is I dont want to return null in case if source1 and source3 is null and rather I will map the available details from source2 and proceed. I have gone through the mapstruct docs, But unfortunately I couldn't find any possible solution for this. Do we have any solution in mapstruct for the above usecase or do we need to write custom logic to handle the above case. Any pointer here is much appreciated and thanks in advance.


Solution

  • Here My issue is I dont want to return null in case if source2 and source3 is null and rather I will map the available details from source1 and proceed.

    Looking at the generated snippet by MapStruct the exact thing that is being asked is generated.

    public SomeClass map(Source1 source1, Source2 source2, Source3 source3)(
        if ( source1 == null && source2 == null && source3 == null ) {
            return null;
        }
    
        // rest of mmapping
    }
    

    This means that if source1 is not null and source2 and source3 are null then then mapping will not return null, but it will use source1 to do the mapping