Reputation: 103
How to use ModelMapper
to convert Entity to DTO when the entity has OneToMany
relationship with another entity.
I have one Entity Student
@Getter
@Setter
public class Student{
private int name;
private Set<Department> department;
}
@Getter
@Setter
public class Department{
private int name;
}
@Getter
@Setter
public class StudentDto{
private int name;
private Set<DepartmentDto> departmentDto;
}
@Getter
@Setter
public class DepartmentDto{
private int name;
private int name;
}
I am using the below method to convert Entity to DTO:-
private List<StudentDto> convertToDto(List<Student> Student) {
List<StudentDto> studentDtos= new LinkedList<>();
Iterator<Student> student= student.iterator();
while (student.hasNext()) {
Student student2= student.next();
studentDtos.add(modelMapper.map(student2, StudentDTo.class));
}
return studentDtos;
}
When i am doing this i am calling this in my controller and there i can see that Department DTo is coming as null. Can you tell me where i am doing wrong?
Upvotes: 0
Views: 999
Reputation: 5424
just change StudentDto
to this:
@Getter
@Setter
public class StudentDto{
private int name;
private Set<DepartmentDto> department;
}
or better naming may be:
@Getter
@Setter
public class Student {
private int name;
private Set<Department> departments;
}
@Getter
@Setter
public class StudentDto {
private int name;
private Set<DepartmentDto> departments;
}
Upvotes: 1