简体   繁体   中英

MapStruct nullValueMappingStrategy primitive to bean return default bean instead of null value

MapStruct version: 1.4.1.Final

When I am trying to map an integer to a bean, when the integer is null the target is still being created as a default object instead of null

@Mapper(componentModel = "spring", nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL, nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_NULL)
public interface CompanyMapper { // NOSONAR

  CompanyMapper INSTANCE = Mappers.getMapper(CompanyMapper.class);

  @Mapping(source = "parentId", target = "parent.id")
  Company toEntity(RequestCompany request);

}

The code generated

    @Override
    public Company toEntity(RequestCompany request) {
        if ( request == null ) {
            return null;
        }

        CompanyBuilder company = Company.builder();

        company.parent( requestCompanyToCompany( request ) );
        // Removed for simplicity

        return company.build();
    }
    
    protected Company requestCompanyToCompany(RequestCompany requestCompany) {
        if ( requestCompany == null ) {
            return null;
        }

        CompanyBuilder company = Company.builder();
        
        // Should verify if the parentId is null and 
        // return null if condition is met
        company.id( requestCompany.getParentId() );

        return company.build();
    }

Edit: related to https://github.com/mapstruct/mapstruct/issues/1166#issuecomment-353742387

This works as intended. MapStruct can't know which properties of your source object need to be considered as crucial properties for performing the mapping.

In order to achieve what you are looking for you will have to provide your own mapping method for it.

eg

@Mapper(componentModel = "spring", nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL, nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_NULL)
public interface CompanyMapper { // NOSONAR

  default Company toEntity(RequestCompany request) {
    if (request == null || request.getParentId() == null) {
      return null;
    }

    return toEntity2(request);
  }
  
  @Named("ignoreForOtherMethods")
  @Mapping(source = "parentId", target = "parent.id")
  Company toEntity2(RequestCompany request);

}

Note: It is recommended not to use Mapper#getMapper when using the spring component model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM