Mapstruct - 忽略嵌套集合中的字段 - 克隆对象时不起作用

Mapstruct - ignore fields from nested collection - not working when cloning the object

我有以下实体 类 和类似的 DTO 类:

class Car {
    Long id;
    List<Owner> ownerList;
}

class Owner {
    Long id;
    String name;
}

我使用具有以下映射的 MapStruct 到:

  1. 不带 ID 复制到 CarDto
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "ownerList", qualifiedByName = "withoutIdDto")
    CarDto carToCarDto(Car car);

    @Named("withoutIdDto")
    @Mapping(target = "id", ignore = true)
    OwnerDto mapOwnerDtoWithoutId(Owner owner);
  1. 无 ID 克隆
    @Mapping(target = "id", ignore = true) //ignore Car.id
    @Mapping(target = "ownerList", qualifiedByName = "withoutId")
    Car copyCar(Car car);

    @Named("withoutId")
    @Mapping(target = "id", ignore = true) //ignore Owner.id
    Owner mapOwnerWithoutId(Owner owner);

问题是:

为 carToCarDto() 生成的映射器正在调用 mapOwnerDtoWithoutId(),但 copyCar 方法没有调用 mapOwnerWithoutId()。这是生成的方法的片段:

public Car copyCar(Car car) {
    if (car == null) {
        return null;
    } else {
        Car car1 = new Car();
        List<Owner> list = car.getOwnerList();
        if (list != null) {
            car1.setOwnerList(new ArrayList(list)); // no reference to mapOwnerWithoutId
        }

        return car1;
    }
}

public CarDto carToCarDto(Car car) {
    if (car == null) {
        return null;
    } else {
        CarDto carDto = new CarDto();
        carDto.setOwnerList(this.ownerListToOwnerDtoList(car.getOwnerList())); //ownerListToOwnerDtoList () calls mapOwnerDtoWithoutId
        return carDto;
    }
}

我正在关注重现此项目的项目。知道如何修复测试 CarMapperTest 吗?

https://github.com/gtiwari333/mapstruct-failing-test-same-object-copy

MapStruct 的处理方式有所不同 1.列出源元素和目标元素相同的地方(在一行中) 2. 源和目标不同的列表。

我个人不喜欢这种差异,但它已经存在很长时间了。我有点担心当我们改变这个(并且总是做 2.)时,我们可能会破坏一些实现。

话虽如此,我仍然认为 MapStruct 应该更喜欢可用的方法而不是直接映射。请在我们的 GitHub 上为此写一个问题并参考这个问题。

现在,解决这个问题的方法是定义一个像这样的中间映射方法:List map(List s)。 MapStruct 将生成那个实现并调用它。