是否可以将值从父对象传播到嵌套对象的集合?例如
源 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,因此我想将 userId 从 CarDto 映射到wheels集合中每个对象上的 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
将从中获取 userId 的对象CarDto
在映射汽车之前,然后将其设置在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);
}
}
The CarContext
将被传递给轮映射方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)