Modelmapper with combined properties

1.7k views Asked by At

Given the following to models

class Project {
  String groupId;
  String artifactId;
  String version;
}

class ProjectWithId {
  String id;
  String groupId;
  String artifactId;
  String version;
}

How would I use ModelMapper correctly to combine the values of groupId, artifactId and version? E.g. is there some way to avoid the following:

ProjectWithId projectWithId = modelMapper.map(project, ProjectWithId.class);
projectWithId.setId(project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion());
1

There are 1 answers

0
Yogi On

You need to create Custom Converter to combine 3 properties i.e. groupId,artifactId and version.

For e.g.

Converter<String, String> converter = new Converter<String, String>() {
  public String convert(MappingContext<String, String> context) {
    Project project = (Project) context.getParent().getSource();
    return project.groupId + project.artifactId+ project.version;
  }
};

Use this converter while mapping

modelMapper.addConverter(converter);