How to convert a JPA OneToMany relationship to DTO
dto, java, jpa
Solution
It won't be an infinite loop because you have to use the PlanDTO object result which you have just created before the loop. See the code below.
Note : Still I suggest to go for a framework which will do this stuff for you.
public class PlanAssembler {
public static PlanDTO makeDTO(Plan p) {
PlanDTO result = new PlanDTO();
result.setProperty(p.getProperty);
...
for (Activity a: p.getActivity()) {
ActivityDTO activityDTO = new ActivityDTO();
// Here I need to iterate over each activity to convert it to DTO
// But in ActivityAssembler, I also need PlanDTO
//Code to convert Activity to ActivityDTO.
activityDTO.setPlan(result);
}
Problem
I have a class `Plan` in which there is a list of `Activity`. The `Activity` class has a reference to a single `Plan`. Hence there is a OneToMany relationship like this: ``` @Entity public class Plan { @OneToMany(mappedBy = "Plan") private List<Activity> activities; } @Entity public class Activity { @ManyToOne @JoinColumn(name= "PLAN_ID") private Plan plan; } ``` I need to convert them to DTOs to be sent to presentation layer. So I have an assembler class to simply convert domain objects to POJO. ``` public class PlanAssembler { public static PlanDTO makeDTO(Plan p) { PlanDTO result = new PlanDTO(); result.setProperty(p.getProperty); ... for (Activity a: p.getActivity()) { // Here I need to iterate over each activity to convert it to DTO // But in ActivityAssembler, I also need PlanDTO } ``` As you can see, in `PlanAssembler`, I need to iterate over all activities and convert them to `ActivityDTO` but the trouble is, in `ActivityAssembler` I also need the `PlanDTO` to construct the `ActivityDTO`. It's gonna be an infinite loop. How can I sort this out? Please help.