将其他参数传递给MapStruct映射器

时间:2018-05-24 20:33:17

标签: java mapping mapstruct

Haven没有想出如何传递额外的论据或替代方案。

目前我正在映射Order和OrderLines。两个对象都不同,需要@mappings。示例我有一个Order和OrderRequest对象都是不同的,需要@Mappings注释来映射值,与OrderLines相同。

我创建了以下映射器

  • OrderMapper(uses = OrderLineMappers.class)
  • OrderLineMappers(uses = OrderLineMapper.class)
  • OrderLineMapper

所以我的问题是OrderLine需要Order对象的OrderId。但是在OrderLineMapper中,它传递OrderLine而不是Order。如何将OrderId发送到OrderLineMapper?目前我让OrderMapper执行@AfterMapper,循环遍历orderLines并使用OrderId填充。

任何帮助都会很棒。

Class OrderMapper

@Mapper(componentModel = "spring",  uses = {OrderLineMappers.class})
public abstract class OrderMapper {

@AfterMapping
protected void orderRequestFromOrder( Order order, @MappingTarget 
OrderRequest orderRequest ) {

    //Wanting to do this at the OrderLineMapper class and not here
    String orderId = order.getId();
    List<OrderLineRequest> lines = orderRequest.getOrderLines();
    List<OrderLineRequest> updatedLines = new ArrayList<>();
    for (OrderLineRequest line : lines) {
        line.setOrderId(orderId);
        updatedLines.add(line);
    }
    orderRequest.setOrderLines(updatedLines);
}

@Mappings({
    @Mapping( source = "orderId", target = "id" ),
    @Mapping( source = "orderNumber", target = "order_number" ),
    @Mapping( source = "orderLines", target = "orderLines")
})
public abstract Order orderRequestToOrder(OrderRequest orderRequest);

Class OrderLineMappers

@Mapper(componentModel = "spring",  uses = {OrderLineMapper.class})
public interface OrderLineMappers {

    List<OrderLine> orderLines(List<OrderLineRequest> orderLineRequest);

    @InheritInverseConfiguration
    List<OrderLineRequest> orderLineRequests(List<OrderLine> orderLine); 

}

Class OrderLineMapper

@Mapper(componentModel = "spring")
public abstract class OrderLineMapper {
    @Mappings({
        @Mapping( target = "orderId", source = "orderLineId" ),
        @Mapping( target = "order_line_number", source = "orderLineNumber")

    })
    public abstract OrderLine orderLineRequestToOrderLine(OrderLineRequest orderLineRequest);
}

再次尝试将OrderId传递给OrderLineMapper。不知道怎么做。

1 个答案:

答案 0 :(得分:0)

你真的不能这样做。你可以做的是使用@Context并在其中执行你的逻辑。您可以在上下文中使用@AfterMapping@BeforeMapping来存储Order ID,并在执行期间使用该ID