Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelMapper skip a field

Tags:

modelmapper

I would like to map between UserDTO and User, but excluding one field, say city. How can I do that, cause I though that this approach would work, but it doesn't:

ModelMapper modelMapper = new ModelMapper();

modelMapper.typeMap(UserDTO.class,User.class).addMappings(mp -> {
    mp.skip(User::setCity);
});
like image 360
user3529850 Avatar asked Mar 02 '18 17:03

user3529850


3 Answers

Because of the generic parameters, we couldn't use the lambda expression.

ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(new PropertyMap<Dto, Source>() {
                @Override
                protected void configure() {
                    skip(destination.getBlessedField());
                }
            });
like image 59
Muhammed Ozdogan Avatar answered Dec 31 '22 23:12

Muhammed Ozdogan


For the configuration to work need to add:

modelMapper.getConfiguration().setAmbiguityIgnored(true);

E.g.

ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setAmbiguityIgnored(true);
modelMapper.addMappings(clientPropertyMap);
modelMapper.map(UserDTO, User);


PropertyMap<UserDTO, User> clientPropertyMap = new PropertyMap<UserDTO, User>() {
    @Override
    protected void configure() {
        skip(destination.getCity());
    }
};
like image 42
Sergiu Ionita Avatar answered Jan 01 '23 00:01

Sergiu Ionita


For the configuration to work need to add:
modelMapper.getConfiguration().setAmbiguityIgnored(true);

This is true only when the destination field matches to multiple source fields. Skipping the setting of a destination field will work without the above if there is either a 1-1 or a 0-1 match between source-destination.

like image 31
TheAppFoundry Avatar answered Jan 01 '23 00:01

TheAppFoundry