Is there a way configure model mapper to automatically map parent id to parent ids in nested child object?
Parent entity
@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;
Child entity
@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;
Parent DTO
public class ParentDto {
private Long id;
private String name;
private List<ChildDto> children;
Child DTO
public class ChildDto {
private Long id;
private Long parentId;
private String name;
Currently Im using model mapper and it conversion works for the most part, and it creates a ParentEntity object with a list of ChildEntity object. Now Im looking for a way to populate the "parentId" field in each ChildEntity with modelmapper. Thanks in advance!
/*
{
id: 1,
name: "dad",
children: [
{
id:10,
name: "child",
},
{
id:20,
name: "child2",
}
]
}
*/
modelMapper.map(parentDto, ParentEntity.class)
The challenge is that when
ChildDtois mapped you must have access to theParentDtothat has theListchildren in which theChildDtoto be mapped is added. Otherwise the mapper does not know about that id.Luckily you can access
ParentDtowith a little help from aorg.modelmapper.Converter. Implement this interface like:Then use it like:
and
ChildDtothat has noparentIdshould still be mapped toChildEntitywithparentId.