I have the following entities:
@Entity, Getter, Setter
public class Plant { // the "child" class
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private PlantGroup plantGroup;
}
@Entity, Getter, Setter
public class PlantGroup {
private String name;
@Setter(AccessLevel.NONE)
@OneToMany(mappedBy = "plantGroup")
private List<Plant> plants = new ArrayList<>();
public void addPlant(Plant plant) {
plants.add(plant);
plant.setPlantGroup(this);
}
}
I want to map from the following DTO:
@Getter
@Setter
public class PlantGroupDTO {
private String name;
private List<Long> plantIds;
}
This is my mapper:
@Mapper(componentModel = "spring", collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public abstract class PlantGroupMapper {
@Autowired
PlantService plantService;
public abstract PlantGroup map(PlantGroupDTO dto);
public List<Plant> map(List<Long> ids) {
// I would expect this to be called
}
}
What I want to achieve is: while mapping from my List<Long> plantIds
to List<Plant> plants
I am not only retrieving them from the service, but also add them to the return value PlantGroup
by calling plantGroup.addPlant(plant);
However I don't understand the error message:
Can't map property "List<Long> plants" to "Plant plants". Consider to declare/implement a mapping method: "Plant map(List<Long> value)".
Why does it want to map the List to a single entity? Is there another best practice to force Mapstruct to use the bidirectional add* method?
Basically I just need this line to be executed:
dto.getPlantIds()
.forEach(plantId ->
plantGroup.addPlant(plantService.findById(plantId)
.orElseThrow(() -> new EntityNotFoundException(plantId, Plant.class))));