gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:39:48 30 4
gpt4 key购买 nike

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

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

class Owner {
Long id;
String name;
}

我使用 MapStruct 进行以下映射:

  1. 复制到 CarDto,无需 ID
    @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);
  • 没有 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 将生成该实现并调用它。

    关于java - Mapstruct - 忽略嵌套集合中的字段 - 克隆对象时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57189819/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com