Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map struct : When source is null, target should NOT be set to null

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

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

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

The complete generated code is here
https://github.com/mapstruct/mapstruct/issues/1306

Thanks

like image 222
Malathi Damodaran Avatar asked Sep 10 '25 17:09

Malathi Damodaran


1 Answers

@Mapper( nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE )
like image 104
Alex Avatar answered Sep 12 '25 09:09

Alex