【问题标题】:MapStruct mapping on objects of type ListList 类型对象上的 MapStruct 映射
【发布时间】:2021-03-25 14:17:52
【问题描述】:

我正在尝试将 MapStruct 用于类似于以下的结构:

@Data
public class ClassAEntity {
  private int id;
  private String name;
  private String numT;
  private List<ClassBEntity) bs;
}

@Data
public class ClassBEntity {
  private int id;
  private String name;
  private String numT;
  private List<Other> oc;
}

@Data
public class ClassA {
  private int id;
  private String name;
  private List<ClassB) bs;
}

@Data
public class ClassB {
  private int id;
  private String name;
  private List<Other> oc;
}

在界面中我添加了如下映射:

ClassAEntity map(ClassA classA, String numT)

我收到警告,因为它无法将 numT 映射到 classBEntity.numT 并且我无法通过以下方式使用 @Mapping 添加它:

@Mapping(source = "numT", target = "bs[].numT")

另一方面,我需要忽略 classBEntity 的参数 oc,因为“Other”对象包含 classAEntity 并形成一个循环对象。 (因为我使用 oneToMany JPA)。我尝试了以下方法:

@Mapping(target = "bs[].oc", ignore = true)

感谢您的帮助

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    MapStruct 不支持为集合定义嵌套映射。您必须定义更明确的方法。

    例如,要将 numT 映射到 bs[].numT 并忽略 bs[].oc,您需要执行以下操作:

    @Mapper
    public MyMapper {
    
        default ClassAEntity map(ClassA classA, String numT) {
            return map(classA, numT, numT);
        }
        
        ClassAEntity map(ClassA classA, String numT, @Context String numT);
    
        @AfterMapping
        default void setNumTOnClassBEntity(@MappingTarget ClassBEntity classB, @Context String numT) {
            classB.setNumT(numT);
        }
    
        @Mapping(target = "oc", ignore = "true")
        ClassBEntity map(ClassB classB);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-06
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      相关资源
      最近更新 更多