Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapStruct - How to set different null strategy for different mapping methods?

Tags:

mapstruct

I want to have a single Mapper class with both create and update methods. The generated code for create method is fine, but in case of update, I want to set the properties in the target, only if they are not null in the source.

How do I do it with mapStruct?

The confusion arises because the nullValueMappingStrategy is being defined at Mapper or Mapping level.

If I set that value at Mapper level, it will be applied to all methods, including create and update.

@Mapper // If I define null strategy here, it will be applied to all methods
public interface AmcPkgMapper {

    AmcPkgMapper MAPPER = Mappers.getMapper(AmcPkgMapper.class);

    AmcPackage create(AmcPackageRequest amcPackageRequest);

    // How to define the null strategy here??
    void update(AmcPackageRequest amcPackageRequest, @MappingTarget  AmcPackage amcPackage);

}

And if I set it on the method with Mapping, then it expects me to define a target object, for which I probably need a wrapper object and somehow map all the internal properties inside that.

@Mapping(target = "amcPackage", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
void update(AmcPackageRequest amcPackageRequest, @MappingTarget AmcPackageWrapper amcPackageWrapper);

With the above method, the generated code looks as below, which isn't going inside amcPackage to set all properties.

@Override
public void update(AmcPackageRequest amcPackageRequest, AmcPackageWrapper amcPackageWrapper) {
    if ( amcPackageRequest == null ) {
        return;
    }
// nothing is mapped actually!!
}

Is there a simple way to do it without creating separate mapper classes for create and update?

like image 978
gaganbm Avatar asked Jan 14 '19 00:01

gaganbm


1 Answers

Got it done with @BeanMapping

@BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
            nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
void update(AmcPackageRequest amcPackageRequest, @MappingTarget AmcPackage amcPackage);
like image 176
gaganbm Avatar answered Oct 29 '22 13:10

gaganbm