【问题标题】:Modelmapper with combined properties具有组合属性的模型映射器
【发布时间】:2017-08-30 22:47:14
【问题描述】:

给定以下模型

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());

【问题讨论】:

    标签: java modelmapper


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 2012-09-23
      • 1970-01-01
      • 2023-04-10
      • 2012-03-27
      • 2015-04-13
      • 2016-06-13
      • 2017-04-04
      • 1970-01-01
      相关资源
      最近更新 更多