ModelMapper - 在具有该属性的关系的实体中映射 DTO 的属性 [英] ModelMapper - Map a DTO's property inside an Entity that has a Relationship that has this property
问题描述
早上好
我正在使用 ModelMapper 将 DTO 映射到实体,反之亦然,对此我有一个问题.
I am using the ModelMapper to map the DTOs to the Entities and vice versa and related to this I have one question.
1) 当我从 SonController 获取 SonDTO 时,我需要将长的 MotherId 映射到实体 Son,但在那里我有实体 Mother Mother 建立关系,并且内部具有 id.那么我如何将这个 SonDTO MotherId 映射到实体 Mother Mother,反之亦然?
1) When I'm getting SonDTO from SonController, I need to map the long motherId to Entity Son, but there I have the Entity Mother mother making the relationship and that has the id internally. So how do I map this SonDTO motherId into the Entity Mother mother and vice versa?
在类下面:
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
.
You can use a PropertyMap
for your entity and add it to the 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
) 属性.
You don't have to create a mapping for the SonDTO
object because the modelMapper is looking through your attributes' name and uses a default matching strategy and SonDTO
's attributes name are just enough to not use another strategies and match the correct source (Son
) attributes.
链接:
1) 匹配过程(非常重要):这里
2) 匹配策略(非常重要):这里
3) 示例(重要):此处.(请注意这里的属性命名.)
3) Example (important) : here. (Please pay attention here at the attribute naming.)
这篇关于ModelMapper - 在具有该属性的关系的实体中映射 DTO 的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!