首页 > 解决方案 > How to write mapper(MapStruct) from a list type to a list

问题描述

We have a class representing Animal transfering attribute value to WildAnimal.Both types are rather similar, only the attributes have different names and the type attribute is same.

public class Animal{
    private List<Cat> cats;
}

public class Cat {
    private String colour;
    private Integer weight;
}

public class WildAnimal{

    private List<WildCat> wildCats;
}
public class WildCat {
    private String shade;
    private Integer mass;
}

@Mapper
public interface AnimalMapper {
  @Mapping( source = "cats", target = "wildCats")

  WildAnimal animalTowildAnimal(Animal animal);
}

This is not working. Could you please tell me the correct way of doing it. Thank you in adavance.

标签: javaspring-bootmapstruct

解决方案


您必须提供与您的“父”映射操作相关的其他类型的映射说明。

例子:

@Mapper
public interface AnimalMapper {

  @Mapping(source = "colour", target = "shade")
  @Mapping(source = "weight", target = "mass")
  WildCat catToWildCat(Cat cat);

  @Mapping(source = "cats", target = "wildCats")
  WildAnimal animalToWildAnimal(Animal animal);
}

推荐阅读