问题描述
有没有一种方法可以配置模型映射器以自动将父ID映射到嵌套子对象中的父ID?
父实体
@Entity
@Table(name = "parent")
public class ParentEntity {
@Id
@Column(name = "id")
private Long id;
@Basic
@Column(name = "name")
private String name;
@OnetoMany(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id",referencedColumnName = "id")
private List<ChildEntity> child;
子实体
@Entity
@Table(name = "child")
public class ChildEntity {
@Id
@Column(name = "id")
private Long id;
@Basic
@Column(name = "parent_id")
private Long parentId;
@Basic
@Column(name = "name")
private String name;
家长DTO
public class ParentDto {
private Long id;
private String name;
private List<ChildDto> children;
儿童DTO
public class ChildDto {
private Long id;
private Long parentId;
private String name;
目前,Im使用模型映射器,并且它的转换大部分工作,并且它创建带有ParentEntity对象列表的ParentEntity对象。现在,我正在寻找一种用modelmapper填充每个ChildEntity中“ parentId”字段的方法。预先感谢!
/*
{
id: 1,name: "dad",children: [
{
id:10,name: "child",},{
id:20,name: "child2",}
]
}
*/
modelmapper.map(parentDto,ParentEntity.class)
解决方法
面临的挑战是,在映射ChildDto
时,您必须有权访问具有ParentDto
孩子的List
,其中ChildDto
要映射的已添加。否则,映射器将不知道该ID。
幸运的是,您可以在ParentDto
的帮助下访问org.modelmapper.Converter
。像这样实现此接口:
public Converter<ChildDto,ChildEntity> converter = new Converter<>() {
private final ModelMapper mm = new ModelMapper();
@Override
public ChildEntity convert(MappingContext<ChildDto,ChildEntity> context) {
// map it first normally
ChildEntity ce = mm.map(context.getSource(),ChildEntity.class);
try {
// 1st parent is the List 2nfd is the ParentDto
ParentDto parentDto = (ParentDto)context.getParent().getParent().getSource();
ce.setParentId(parentDto.getId());
} catch (Exception e) {
// well,maybe it was not ParentDto that expected to be the grandparent.
}
return ce;
}
};
然后像这样使用它:
ModelMapper mm = new ModelMapper();
mm.addConverter(converter);
和没有ChildDto
的{{1}}应该仍然用parentId
映射到ChildEntity
。