映射结构:当源为空时,目标不应设置为空 [英] Map struct : When source is null target should NOT be set to null

查看:135
本文介绍了映射结构:当源为空时,目标不应设置为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to map nested properties using mapstruct 1.2.0.CR2. (Example map customer.address.houseNumber to userDTO.homeDTO.addressDTO.houseNo ).

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

Expectation : I do not want to set the addressDTO to null when customer.address is null. Since addressDTO contains "countyname" and other properties which are already set from other different sources.

请告知是否有我可以设置的属性/设置,以便在源为空时目标不会设置为空.

Please advice if there is property/setting that I could set so that the target it not set to null when source is null.

@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)  ;

}

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

I initially tried in single mapping like below

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

然后尝试拆分映射,基于 https://github.com/mapstruct/映射结构/问题/649.

Then tried splitting up the mapping, based on https://github.com/mapstruct/mapstruct/issues/649.

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

Both approaches does not produce the expected result/ Generated method code

 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.
        }**
    }

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

谢谢

推荐答案

@Mapper( nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE )

这篇关于映射结构:当源为空时,目标不应设置为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆