gpt4 book ai didi

java - 使用模型映射器将实体转换为 DTO 正在下降

转载 作者:行者123 更新时间:2023-12-02 11:37:00 24 4
gpt4 key购买 nike

当实体与另一个实体具有 OneToMany 关系时,如何使用 ModelMapper 将实体转换为 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;
}

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

最佳答案

只需将 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;
}

关于java - 使用模型映射器将实体转换为 DTO 正在下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48865171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com