2017-08-30 103 views
1

考慮下面以模型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

您需要創建自定義轉換到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);