java - ModelMapper - 将 DTO 的属性映射到具有该属性的关系的实体内

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

早上好

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

1) 当我从 SonController 获取 SonDTO 时,我需要将长 motherId 映射到实体 Son,但是实体 Mother mother 建立了关系,并且内部具有 id。 那么如何将这个 SonDTO motherId 映射到 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;
}

最佳答案

您可以为您的实体使用 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 。 (这里的属性命名请注意。)

关于java - ModelMapper - 将 DTO 的属性映射到具有该属性的关系的实体内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60826669/

相关文章:

java - 继承指定Type的泛型类时会发生Type Erasure吗?

java - 在 eclipse、cmd 和 jar 中运行时的工作目录

java - 无法解析 'javax.persistence.EntityManager' 的 bean

css - Springboot - 资源解释为样式表但以 MIME 类型文本/htm 传输

spring - Spring Boot Cloud Kubernetes配置不适用于多个Pod

java - 设置 Spring Boot Servlet 初始化程序时遇到问题

java - 使用光照时,顶点着色不适用于动态创建的网格

java - 我应该将超时设置为 "getting connection from pool"吗?

java - 在非预定义值上请求映射?

java - 如何使用JUnit测试Spring Boot中的服务层代码?