早上好
我正在使用 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/