【问题标题】:mapstruct - Propagate parent field value to collection of nested objectsmapstruct - 将父字段值传播到嵌套对象的集合
【发布时间】:2018-12-22 22:50:44
【问题描述】:

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

源 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 映射到 WheelDto 上的 lastUserId 我试过了

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

但没有运气

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    目前无法传递属性。但是,您可以通过@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 将被传递给车轮映射方法。

    【讨论】:

    • 我使用了第二种方法。很好的解决方案,对我有用。
    • @Filip 您能否添加一个从映射器的客户端代码调用“@Context”变体中生成的映射器的示例?如果我理解正确的话,应该是map(carDto, new CarContext()),对吧?因此,您必须始终从客户端代码显式创建一个虚拟上下文对象?
    • 如果CarMapper 将在另一个使用@Mapper(uses = CarMapper.class) 的映射器中使用呢?另一个映射器如何调用Car map(CarDto carDto, @Context CarContext context);?它将在哪里获得CarContext 对象?还是我需要在所有其他映射器中添加此参数,这将隐式使用CarMapper
    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 2019-08-05
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    相关资源
    最近更新 更多