Sai A
Sai A

Reputation: 241

Prevent Null Check in MapStruct

Mapper

@Mapping(target="subjectName", source="courseName")
Target map(Source source);

MapStruct generated method

public Target map(Source source) {
        if ( source == null ) {
            return null;
        }
        Target target = new Target();
        target.setSubjectName( source.getCourseName() );
        return target;
    }

Now, my requirement is to prevent null check on source in MapStruct generated method. How can acheive that ?

Upvotes: 1

Views: 2571

Answers (2)

Sanket Patel
Sanket Patel

Reputation: 259

@Mapping(target="subjectName", source="courseName",qualifiedByName = "yourCustomMethod")
Target map(Source source);

@Named("yourCustomMethod")
default Target yourCustomMethod(Source source){
if ( source == null ) {
        return null;
    }
    Target target = new Target();
    target.setSubjectName( source.getCourseName() );
    return target;
}

I call it copying from the compiler :D

Upvotes: 0

Filip
Filip

Reputation: 21423

The only way to achieve that in the moment is to define your own custom public Target map(Source source) method. There is already an open issue for MapStruct to support the @Nullable, @NonNull annotations as well, but it still has not been done.

Upvotes: 0

Related Questions