【问题标题】:Mapstruct - ignore fields from nested collection - not working when cloning the objectMapstruct - 忽略嵌套集合中的字段 - 克隆对象时不起作用
【发布时间】:2019-07-24 19:16:00
【问题描述】:

我有以下实体类和类似的 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()。这是生成方法的 sn-p:

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

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    MapStruct 的处理方式有所不同 1. 源元素和目标元素相同的列表(对齐) 2. 源和目标不同的列表。

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

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

    现在,一种解决方法是定义一个中间映射方法,如下所示:List map(List s)。 MapStruct 会为那个生成实现并调用它。

    【讨论】:

    • 谢谢,添加 List map (List s) 有效。我将在 GitHub 上创建一个问题。 @IterableMapping(qualifiedByName = "withoutId") List&lt;Owner&gt; copyOwners(List&lt;Owner&gt; owners);
    猜你喜欢
    • 2020-03-07
    • 1970-01-01
    • 2017-08-04
    • 2021-04-12
    • 1970-01-01
    • 2016-12-12
    • 2014-05-06
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多