使用Model Mapper将实体转换为DTO正在下降

时间:2018-02-19 11:26:10

标签: java dto modelmapper

当实体与其他实体有ModelMapper关系时,如何使用OneToMany将实体转换为DTO。

我有一个实体学生

    @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;
    }

我使用以下方法将实体转换为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;
    }

当我这样做的时候,我在我的控制器中调用它,在那里我可以看到Department DTo即将为空。你能告诉我我在哪里做错了吗?

1 个答案:

答案 0 :(得分:1)

只需将StudentDto更改为:

@Getter
@Setter
public class StudentDto{
     private int name;
     private Set<DepartmentDto> department;
}

或更好的命名可能是:

@Getter
@Setter
public class Student {
    private int name;
    private Set<Department> departments;
}

@Getter
@Setter
public class StudentDto {
    private int name;
    private Set<DepartmentDto> departments;
}