是否可以将父对象的值传播到嵌套对象的集合?例如
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,因此我想在wheel集合中的每个对象上将CarDto的userId映射到WheelDto的lastUserId 我尝试过
@Mapping(target = "wheels.lastUserId", source = "userId")
但没有运气
答案 0 :(得分:3)
当前无法传递属性。但是,您可以通过@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()));
}
}
如果您只想通过Wheel
进行一次迭代,则可以传递一个@Context
对象,该对象将从CarDto
获取用户ID,然后再映射汽车,然后将其设置在后映射中的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
将被传递到车轮映射方法。