mapstruct - 将父字段值传播到嵌套对象的集合

mapstruct - Propagate parent field value to collection of nested objects

是否可以将值从父对象传播到嵌套对象集合?例如

源 DTO 类

class CarDTO {
  private String name;
  private long userId;
  private Set<WheelDto> wheels; 
};

class WheelDto {
  private String name;
}

目标实体类

class Car {
  private String name;
  private long userId;
  private Set<Wheel> wheels; 
};

class Wheel {
  private String name;
  private long lastUserId;
}

如您所见,我在 WheelDto 上没有 lastUserId,因此我想将 wheels 集合中每个对象上的 userId 从 CarDto 映射到 WheelDto 上的 lastUserId 我试过了

@Mapping(target = "wheels.lastUserId", source = "userId") 

但运气不好

目前无法传递 属性。但是,您可以通过 @AfterMapping 和/或 @Context.

解决此问题

汽车映射后更新车轮

虽然这意味着您需要在 Wheel 上迭代两次。它看起来像

@Mapper
public interface CarMapper {

    Car map(CarDto carDto);

    @AfterMapping
    default void afterCarMapping(@MappingTarget Car car, CarDto carDto) {
        car.getWheels().forEach(wheel -> wheel.setLastUserId(carDto.getUserId()));
    }
}

在映射轮时传递@Context 以在映射期间具有状态

如果您只想通过 Wheel 迭代一次,那么您可以传递一个 @Context 对象,该对象会在映射汽车之前从 CarDto 获取 userId,然后设置它在映射后的 Wheel 上。这个映射器看起来像:

@Mapper
public interface CarMapper {

    Car map(CarDto carDto, @Context CarContext context);

    Wheel map(WheelDto wheelDto, @Context CarContext context);

}

public class CarContext {

    private String lastUserId;

    @BeforeMapping
    public void beforeCarMapping(CarDto carDto) {
        this.lastUserId = carDto.getUserId();
    }

    @AfterMapping
    public void afterWheelMapping(@MappingTarget Wheel wheel) {
        wheel.setLastUserId(lastUserId);
    }

}

CarContext 将传递给车轮映射方法。