java 避免MapStruct中的重复Map

mklgxw1f  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(239)

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

///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个Map是完全相同的。有没有一种方法可以不重复这个Map的MapStruct方式?

zc0qhyus

zc0qhyus1#

您可以使用Map组合来避免重复。
例如

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

然后你的mapper看起来像这样:

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

相关问题