ModelMapper - Converter/ AbstractConverter vs Provider
Asked Answered
S

1

6

I'm using ModelMapper to convert some objects to complex DTOs and vice-versa.

Even though I've tried to understand the documentation, I've found hard to understand when to use a Converter or a Provider or an AbstractConverter.

Now, for example, if I want to convert String properties to little DTOs inside of the destination DTO, I'm doing it manually inside an abstract converter.

For instance:

dest.setAddressDTO(new AddressDTO(source.getStreet(), source.getNumber()));

Is though that the right way to do it? When should I use a provider?

And if I want to set properties with conditionals, can I use Conditional from within the converter or that's only when using a PropertyMap ?

Additionally, is it a good practice to use the same modelMapper instance to convert several different types of objects?

Thanks in advance

Sheol answered 5/2, 2018 at 17:51 Comment(0)
S
3

The right way to work with this is to use Converters.

For example, let's say I want to create a converter to convert a dto into a domain object.

So first you define a converter:

private Converter companyDtoToCompany = new AbstractConverter<CompanyDto, Company>() {
    @Override
    protected Company convert(CompanyDto source) {
        Company dest = new Company();

        dest.setName(source.getName());
        dest.setAddress(source.getAddress());
        dest.setContactName(source.getContactName());
        dest.setContactEmail(source.getContactEmail());
     (...)
        dest.setStatus(source.getStatus());

        return dest;
    }
};

Then you add it to the mapper in the configureMappings() method:

    modelMapper = new ModelMapper();

    // Using STRICT mode to prevent strange entities mappin

    modelMapper.getConfiguration()
                     .setMatchingStrategy(MatchingStrategies.STRICT);

    modelMapper.addConverter(companyDtoToCompany);
    // modelMapper.addConverter(otherConverter);
}

And finally you just need to add the mapping methods for those types you can use from your code:

public Company convertCompanyReqDtoToCompany(CompanyDto dto, Class<Company> destinationType) {
        return modelMapper.map(dto, destinationType);
    }
Sheol answered 3/2, 2019 at 11:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.