2

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

Jelly
  • 972
  • 1
  • 17
  • 40
  • Private access via Reflection is problematic in Java 17 and following. If you want to avoid writing boilerplate code, just use `@Getter` and `@Setter` annotations from Lombok on your classes. Or if you want only certain privates fields become accessible: on single field variables. – Jan Feb 25 '22 at 09:55

2 Answers2

3

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);
M. Dudek
  • 978
  • 7
  • 28
  • 1
    Well, `PRIVATE` most likely won't work with Java 17, the latest LTS version, used in Big Companies. So you will have to use getters and setters. I recommend Lombok @Getter and @Setter Annotations for that. – Jan Feb 25 '22 at 09:46
1

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):
pirho
  • 11,565
  • 12
  • 43
  • 70
  • But in @Andrew case, destination class don't have fields in `UNDERSCORE` format, so your solution can't work for him. – M. Dudek Jun 15 '21 at 17:02