Mapstruct:将对象内部的列表映射到对象列表

Mapstruct: Map a list inside an object to a list of objects

鉴于:

public class Car {
  private String plate;
  private List<String> tires;
}

public class TirePlate {
  private String plate;
  private String tire;
}

我想将所有 Car.tires 映射到单独的 TirePlates 中。我知道我可以制作一个 List<String>List<tires> 的映射器,但如果我这样做,我会丢失盘子。

我怎样才能把盘子放在那里?

你可以做的是为列表创建一个自定义映射器,它将获得 plate,然后你将有一个自定义方法从 platetire 映射到TirePlate.

例如:

@Mapper
public interface TireMapper {

    CarDto map(Car car);

    default List<TirePlate> map(List<String> tires, String plate) {
        List<TirePlate> tirePlates = new ArrayList<>(tires.size());

        for(String tire: tires) {
            tirePlates.add(map(tire, plate));
        }
        return tirePlates;
    }

    TirePlate map(String tire, String plate);
}