Convert entities with ModelMapper

Viewed 285

Source and destination entities have difference in style of field-naming (underscore in one, camelCase - in another). So, source:

 public class User {
    private String first_name;
}

Destination:

public class UserDto {
    private String firstName;
}

I have a task to convert entities by ModelMapper automatically - without handle mapping of fields (by getter-setter).

For this aim I tried to configure mapper as follows:

 ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration()
            .setSourceNameTokenizer(NameTokenizers.UNDERSCORE);
        

But this does not work

2 Answers

By default, field matching is disabled, so you have to change flag in configuration.Since your fields are private, you must also include them in your setup:

modelMapper.getConfiguration()
    .setFieldMatchingEnabled(true)
    .setFieldAccessLevel(AccessLevel.PRIVATE);

As already correctly answered by M. Dudek you need to enable the field access separately if you do not want to use getters/setters.

But in order to have it working in both directions you need to also setDestinationNameTokenizer:

modelMapper.getConfiguration()
    .setSourceNameTokenizer(NameTokenizers.UNDERSCORE)
    .setDestinationNameTokenizer(NameTokenizers.UNDERSCORE)
    .setFieldMatchingEnabled(true)
    .setFieldAccessLevel(AccessLevel.PRIVATE);

If willing to use getters/setters then this should be enough:

modelMapper.getConfiguration()
    .setSourceNameTokenizer(NameTokenizers.UNDERSCORE)
    .setDestinationNameTokenizer(NameTokenizers.UNDERSCORE):
Related