I am trying to get a grasp of ModelMapper for the following use case:
class A {
public String name;
public Map<String, ATranslation> translations;
}
class ATranslation {
public String desc;
public String content;
}
class DTO {
public String name;
public String desc;
public String content;
}
Assume Constructors, Getters and Setters.
public class App {
public static void main(String[] args) {
Map<String, ATranslation> translations = new HashMap<>();
translations.put("en", new ATranslation("en-desc","content1"));
translations.put("nl", new ATranslation("nl-desc","content2"));
A entity = new A("John Wick",translations);
System.out.println(App.toDto(entity,"en"));
System.out.println(App.toDto(entity,"nl"));
}
private static DTO toDto(A entity, String lang) {
ModelMapper modelMapper = new ModelMapper();
//how to set up ModelMapper?
return modelMapper.map(entity, DTO.class);
}
}
Without any setup the output is:
DTO(name=John Wick, desc=null, content=null)
DTO(name=John Wick, desc=null, content=null)
A converter does not work:
modelMapper
.createTypeMap(A.class, DTO.class)
.setConverter(new Converter<A, DTO>() {
public DTO convert(MappingContext<A, DTO> context) {
A s = context.getSource();
DTO d = context.getDestination();
d.setDesc(s.getTranslation().get(lang).getDesc());
d.setContent(s.getTranslation().get(lang).getContent());
return d;
}
});
A postConverter does work, but does not seem to be the most ModelMapper way...
modelMapper
.createTypeMap(A.class, DTO.class)
.setPostConverter(new Converter<A, DTO>() {
public DTO convert(MappingContext<A, DTO> context) {
A s = context.getSource();
DTO d = context.getDestination();
d.setDesc(s.getTranslation().get(lang).getDesc()); //tedious, if many fields...
d.setContent(s.getTranslation().get(lang).getContent()); //feels redundant already
return d;
}
});
DTO(name=John Wick, desc=en-desc, content=content1)
DTO(name=John Wick, desc=nl-desc, content=content2)
Is there a better way to use ModelMapper here?