Assume I have such mapping:
@Mapping(source = "parentId", target = "parent.id")
Child map(ChildDto dto, Parent parent);
Now I need to map List of ChildDto to List of Child, but they all have the same parent. I expect to do something like that:
List<Child> map(List<ChildDto> dtoList, Parent parent);
But it doesn't working. Is there any chance to do it?
I found how to implement it with decorators, thanks @Gunnar Here is an implementation:
Beans
Mapper
Decorator
I use
abstract class
, notinterface
for mapper, because in case ofinterface
you couldn't exclude for generation methodmap(List<Child> children, Parent parent)
, and the code being generated is not valid in compile time.That's not possible out of the box as things stand. You could use a decorator or after-mapping method to set the parent to all the child objects afterwards.
I used an
@AfterMapping
as suggested by Gunnar:@AfterMapping public void afterDtoToEntity(final QuestionnaireDTO dto, @MappingTarget final Questionnaire entity) { entity.getQuestions().stream().forEach(question -> question.setQuestionnaire(entity)); }
This made sure all the questions were linked to the same questionnaire entity. This was the final part of the solution for avoiding the JPA error
save the transient instance before flushing
on creating a new parent entity with a list of children.