如何将自定义映射器与带有嵌套值和条件值的mapstruct一起使用

时间:2019-10-11 17:11:56

标签: mapping mapstruct

我正在尝试使用mapstrut将一个对象映射到另一个对象,目前在某些情况下如何使用它面临一些挑战。

public class TargetOrderDto {
    String id;
    String preferedItem;
    List<Item> items;
    String status;
    Address address;

}

public class Item {
  String id;
  String name;
}


public abstract class TargetOrderMapper {

  @Autowired
  private StatusRepository statusRepository;

  @Mappings({
      @Mapping(target = "id", source = "reference"),
      @Mapping(target = "preferedItem", source = ""), // Here I need to loop through these values checking for a single value with a specific tag
      @Mapping(target = "items", source = "items"),   // List of objects to another list of different data types. 
      @Mapping(target = "status", source = "remoteStatus") // may need to extract a value from a repository
  })
  abstract OrderDto toTargetOrderDto(RemoteOrder remoteOrder);

}

// Remote Data

public class RemoteOrder {
  String reference;
  List<Item> items;
  String remoteStatus;
}


public class RemoteItem {
  String id;
  String flag;
  String description;
}

这些是我目前无法解决的当前情况(也许我正在映射一个复杂的对象)。

  1. preferedItem : 为此,我需要遍历订单中的项目,并使用特定的标志标识该项目。 (如果匹配,则采用该值,否则我使用null)
  2. 项目: 我需要将其转换为2个不同列表的列表;列表中的列表,都有各自不同的映射规则。
  3. remoteStatus : 这个有点棘手,我需要从remoteOrder中提取状态,然后使用 statusRepository 在db中查找数据库中的备用映射值。

我们非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您无法使用MapStruct进行业务逻辑。因此,在列表中涉及条件映射时,请保持映射简单,并定义自己的方法。注意:您可以编写自己的方法,然后MapStruct将选择它。另外,从这个自己的实现中,您可以再次引用MapStruct方法。

public abstract class TargetOrderMapper {

  @Autowired
  private StatusRepository statusRepository;

  @Mappings({
      @Mapping(target = "id", source = "reference"),
      @Mapping(target = "preferedItem", source = ""), // Here I need to loop through these values checking for a single value with a specific tag
      @Mapping(target = "items", source = "items"),   // List of objects to another list of different data types. 
      @Mapping(target = "status", source = "remoteStatus") // may need to extract a value from a repository
  })
  abstract OrderDto toTargetOrderDto(RemoteOrder remoteOrder);

  protected List<Item> toItemList(List<Item> items) {
     // do what ever you want..
     // and call toItem during iterating.
  }

  protected abstract Item toItem(Item item);
}

状态也是如此。不久前,我在列表中添加了FAQ entry(主要是关于更新,但我想这里也一样)。

关于查找,您可以使用@MappingContext传递包含访问数据库逻辑的上下文。参见here