如何在Spring Boot中使用Dtos修复具有关系的类的输出?

问题描述 投票:0回答:1

我的班

public class Teacher

与学生有ManyToMany关系:

public class Student

当我返回老师时,我只需要他们的学生证,而不是有关他们学生的完整信息。

我们有两个Dto(DataTransferObject):StudentDto和TeacherDto,带有一些变量。

我该怎么做才能解决这个问题?

我也希望学生仅返回老师的姓名或ID。相反,他们返回完整的dto教师列表。

谢谢。

java class resources dto
1个回答
0
投票
TeacherDto中,您不应该具有StudentDto的列表,而应该具有Integer的列表(如果Integer是ID类型)。比您应该实现一些映射逻辑,例如在构造函数中,例如:

public class TeacherDto { private final Set<Integer> studentIds; public TeacherDto(Teacher teacher) { this.studentIds = teacher.getStudents().stream() .map(Student::getId) .collect(Collectors.toSet()); } public Set<Integer> getStudentIds() { return studentIds; } }

© www.soinside.com 2019 - 2024. All rights reserved.