具有组合属性的Modelmapper

时间:2017-08-30 14:25:30

标签: java modelmapper

给出以下模型

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

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

如何正确使用ModelMapper来组合groupId,artifactId和version的值?例如。有什么方法可以避免以下情况:

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

1 个答案:

答案 0 :(得分:1)

您需要创建自定义转换器以组合3个属性,即groupId,artifactId和version。

例如

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;
  }
};

映射时使用此转换器

modelMapper.addConverter(converter);
相关问题