是否可以将值从父对象传播到嵌套对象的集合?例如
DTO源类
class CarDTO {
private String name;
private long userId;
private Set<WheelDto> wheels;
};
class WheelDto {
private String name;
}
Run Code Online (Sandbox Code Playgroud)
目标实体类别
class Car {
private String name;
private long userId;
private Set<Wheel> wheels;
};
class Wheel {
private String name;
private long lastUserId;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我在WheelDto上没有lastUserId,因此我想在我尝试过的wheels集合中的每个对象上将CarDto的userId映射到WheelDto的lastUserId。
@Mapping(target = "wheels.lastUserId", source = "userId")
Run Code Online (Sandbox Code Playgroud)
但没有运气
当前无法传递属性。但是,您可以通过@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()));
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只想通过进行一次迭代,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);
}
}
Run Code Online (Sandbox Code Playgroud)
在CarContext将被传递到车轮映射方法。
| 归档时间: |
|
| 查看次数: |
832 次 |
| 最近记录: |