映射结构:当源为空时,目标不应设置为空

Mal*_*ran 20 java null target mapstruct

我正在尝试使用 mapstruct 1.2.0.CR2 映射嵌套属性。(示例将customer.address.houseNumber映射到 userDTO.homeDTO.addressDTO.houseNo)。

期望:当 customer.address 为 null 时,我不想将 addressDTO 设置为 null。由于 addressDTO 包含“countyname”和其他已从其他不同源设置的属性。

请告知我是否可以设置某些属性/设置,以便当源为空时目标不会设置为空。

@Mapper( nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS )
public interface CustomerUserMapperNullCheck {

    @Mapping(source="address", target="homeDTO.addressDTO" )
    void mapCustomer(Customer customer, @MappingTarget  UserDTO userDTO)  ;

    @Mapping(source="houseNumber", target="houseNo" )
    void mapCustomerHouse(Address address, @MappingTarget  AddressDTO addrDTO)  ;

}
Run Code Online (Sandbox Code Playgroud)

我最初尝试像下面这样的单一映射

@Mapping(target="homeDTO.addressDTO.houseNo", source="address.houseNumber")
 abstract void mapCustomerHouse(Customer customer, @MappingTarget  UserDTO userDTO)  ; 
Run Code Online (Sandbox Code Playgroud)

然后尝试基于https://github.com/mapstruct/mapstruct/issues/649拆分映射。

两种方法都不会产生预期的结果/生成的方法代码

 protected void customerToHomeDTO(Customer customer, HomeDTO mappingTarget) {
        if ( customer == null ) {
            return;
        }

        if ( customer.getAddress() != null ) {
            if ( mappingTarget.getAddressDTO() == null ) {
                mappingTarget.setAddressDTO( new AddressDTO() );
            }
            mapCustomerHouse( customer.getAddress(), mappingTarget.getAddressDTO() );
        }
        **else {
            mappingTarget.setAddressDTO( null );   // I dont want to else where addressDTO is set to null.
        }**
    }
Run Code Online (Sandbox Code Playgroud)

完整生成的代码在这里
https://github.com/mapstruct/mapstruct/issues/1306

谢谢

小智 36

@Mapper( nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE )
Run Code Online (Sandbox Code Playgroud)