【问题标题】:Avoid duplicate mapping in MapStruct避免 MapStruct 中的重复映射
【发布时间】:2021-05-07 07:10:01
【问题描述】:

我有两个 MapStruct 映射器类,其中一些目标/源类和一些字段完全相同:

  ///Mapper 1
  @Mappings({
          @Mapping(target = "tenantTitleId", expression = "java(order.getProductID())"),
          @Mapping(target = "tenantId", constant = "MGM"),
          @Mapping(target = "titleName", expression = "java(order.getProductDesc())"),
          @Mapping(target = "orders", source = "order", qualifiedBy = ComplexMapper.class),
  })
  @BeanMapping(ignoreByDefault = true)
  public abstract TargetClass toTargetClass(SourceClass sourceClass) throws Exception;

  ///Mapper 2
  @Mappings({
          @Mapping(target = "tenantTitleId", expression = "java(order.getProductID())"),
          @Mapping(target = "tenantId", constant = "MGM"),
          @Mapping(target = "titleName", expression = "java(order.getProductDesc())"),
          @Mapping(target = "orders", source = "order", qualifiedBy = AnotherComplexMapper.class),
  })
  @BeanMapping(ignoreByDefault = true)
  public abstract TargetClass toTargetClass(SourceClass sourceClass) throws Exception;

前 3 个映射完全相同。有没有办法不重复这种 MapStruct 方式的映射?

【问题讨论】:

  • 如果所有这些映射都具有相同的TargetClass 和不同的SourceClass,我认为没有办法实现这一点。您可以尝试使用SourceClass 的一些抽象类并在一个映射方法中映射所有相似的字段,但我还没有测试mapsturct 是否允许您在参数方法中使用抽象类或者它只需要具体类。你可以试试看有没有帮助:)

标签: java objectmapper mapstruct


【解决方案1】:

您可以使用Mapping Composition 以避免重复。

例如

@Retention(RetentionPolicy.CLASS)
@Mapping(target = "tenantTitleId", expression = "productID"),
@Mapping(target = "tenantId", constant = "MGM"),
@Mapping(target = "titleName", expression = "productDesc"),
public @interface CommonMappings { }

然后您的映射器将如下所示:

  ///Mapper 1
  @CommonMappings
  @Mapping(target = "orders", source = "order", qualifiedBy = ComplexMapper.class)
  @BeanMapping(ignoreByDefault = true)
  public abstract TargetClass toTargetClass(SourceClass sourceClass) throws Exception;

  ///Mapper 2
  @CommonMappings
  @Mapping(target = "orders", source = "order", qualifiedBy = AnotherComplexMapper.class)
  @BeanMapping(ignoreByDefault = true)
  public abstract TargetClass toTargetClass(SourceClass sourceClass) throws Exception;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    相关资源
    最近更新 更多