簡體   English   中英

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將為該對象生成實現並調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM