2

I use ModelMapper in my project to map between DTO classes and models.

For example:

public class UserDto {
    private String name;
    private String phone;
    private String email;
}

 
public class User {
    @Id
    private String id;
    private String metaDatal;
    private String name;
    private String phone;
    private String email;
}
 

Here How I map it:

@Autowired
private ModelMapper modelMapper;
modelMapper.map(userDto, user);

As you can see I have metaDatal field in the user model, I want to set this field with a specific value.

Specific field(metaDatal) of the mapped class I want to set this value "abc123". Is there any way to tell map method when it called that, specific filed(for example metaData) should have specific value(for example abc123)?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • Initialise the `metaData` field to the value you want. (and skip the field `typeMap.addMappings(mapper -> mapper.skip(User::setMetaDatal));`) – tgdavies Jul 23 '21 at 06:48

1 Answers1

1

I believe the most flexible way to do this is to implement a simple Converter. Check this:

Converter<UserDto, User> metaData = new Converter<UserDto, User>() {
    // This is needed to convert as usual but not having not registered
    // this converter to avoid recursion
    private final ModelMapper mm = new ModelMapper();
    @Override
    public User convert(MappingContext<UserDto, User> context) {
        User u = context.getDestination();
        mm.map(context.getSource(), u);
        u.setMetaDatal("abc123");
        return context.getDestination();
    }
};

Now it is just to create a TypeMap and set this converter to handle conversion, like:

modelMapper.createTypeMap(UserDto.class, User.class).setConverter(metaData);

before modelMapper.map().

You could also add a getter for metadata in your UserDto, like:

public String getMetaDatal() {
    return "abc123";
}

If it is something that can be derived from UserDto directly and skip the converter part.

pirho
  • 11,565
  • 12
  • 43
  • 70