MapStruct: Map List of objects, when object is mapped from two objects

AlexB picture AlexB · May 16, 2016 · Viewed 29.1k times · Source

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?

Answer

Stephanie picture Stephanie · Jun 15, 2018

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.