【问题标题】:ModelMapper - Map a DTO's property inside an Entity that has a Relationship that has this propertyModelMapper - 在实体中映射 DTO 的属性,该实体具有具有此属性的关系
【发布时间】:2020-03-24 07:36:54
【问题描述】:

早安

我正在使用 ModelMapper 将 DTO 映射到实体,反之亦然,与此相关我有一个问题。

1) 当我从 SonController 获取 SonDTO 时,我需要将 long momId 映射到 Entity Son,但是我有 Entity Mother Mother 建立关系并且在内部具有 id。 那么如何将这个 SonDTO momId 映射到 Entity Mother Mother 中,反之亦然?

类下面:

class SonDTO {
    long id;
    String name;
    int age;
    long motherId;
}
class MotherDTO{
    long id;
    String name;
    int age;
    List<Long> sonsId;
    List<String> sonsName;
}
@Entity
class Mother{

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;

   @Column(name = "name")
   private String name;

   @Column(name = "age")
   private int age;

   @OneToMany(mappedBy = "mother", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
   List<Son> sons;

}
@Entity
class Son{

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;

   @Column(name = "name")
   private String name;

   @Column(name = "age")
   private int age;

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "mother_id")
   private Mother mother;
}

【问题讨论】:

  • 你在这里遇到什么问题??
  • 我正在尝试使用 modelMapper 将 SonDTO 中的 motherId 映射到具有此属性但我做不到的母实体

标签: java spring spring-boot jpa spring-data-jpa


【解决方案1】:

您可以为您的实体使用PropertyMap,并将其添加到ModelMapper

PropertyMap<Mother, MotherDTO> motherMap = new PropertyMap<Mother, MotherDTO>() {
     protected void configure() {
         map().setSonsId(source.getSons()...//here is your choice of coding
         // you can either use streams or simple for loops to transform the
         // entity into a List<Long> 
         );
         //other attributes here
     }
};

最终:

modelMapper.addMappings(motherMap);

您不必为SonDTO 对象创建映射,因为modelMapper 正在查看您的属性名称并使用默认匹配策略,而SonDTO 的属性名称足以不使用其他策略并匹配正确的源 (Son) 属性。

链接:

1) 匹配过程(非常重要):here

2) 匹配策略(非常重要):here

3) 示例(重要):here。 (请注意这里的属性命名。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多