给出以下模型
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());
答案 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);