Mapstrtuct :Nested Object . Create target object only if source element is not Null

Viewed 1945

I want to map nested java objects. Customer.address.houseNumber to userDTO.homeDTO.addressDTO.houseNo.

Expectation: If and only if Customer.address.houseNumber is not null then create homeDTO object under userDTO. Otherwise do not create any target objects.

Problem: I have used "NullValueCheckStrategy.ALWAYS"in the mapper. But mapstruct is checking if address is not null then it creates homeDTO. Inside the address , the houseNumber is NULL. I would like the null check till the houseNumber(leaf/last level object) and then create the target objects.

Please advise how I should achieve this

Here is mapping that I am using.

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

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

}

The generated code is in https://github.com/mapstruct/mapstruct/issues/1303

1 Answers

This is something similar as in mapstruct/mapstruct#879. Currently what you are looking for is not possible.

A way to do it would be do have an @AfterMapping method that will set it back to null if the address.houseNumber is null

Related