简体   繁体   English

MapStruct nullValueMappingStrategy 原语到 bean 返回默认 bean 而不是 null 值

[英]MapStruct nullValueMappingStrategy primitive to bean return default bean instead of null value

MapStruct version: 1.4.1.Final MapStruct 版本: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 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编辑:与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. MapStruct 无法知道源 object 的哪些属性需要被视为执行映射的关键属性。

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.注意:使用spring组件 model 时建议不要使用Mapper#getMapper

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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