获取正确的查询以获取来自多对多spring-jpa关系的学生课程



有人能帮助使用正确的JPQL查询来获取学生的课程吗?

@Entity
@Table(name = "students")
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinTable(name = "students_courses",
joinColumns = {
@JoinColumn(name = "student_id", referencedColumnName = "id",
nullable = false, updatable = false)},
inverseJoinColumns = {
@JoinColumn(name = "course_id", referencedColumnName = "id",
nullable = false, updatable = false)})
private Set<Course> courses = new HashSet<>();
...

@Entity
@Table(name = "courses")
public class Course implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
@ManyToMany(mappedBy = "courses", fetch = FetchType.LAZY)
private Set<Student> students = new HashSet<>();
...

在学生存储库中,我创建了以下JPQL查询:

public interface StudentRepository extends CrudRepository<Student, Long> {
/*THE QUERY SHOULD GO HERE */
@Query("")
List<Course> getStudentCourses(Long studentId);
}

我从StudentController打来的电话:

@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
public StudentRepository studentRepository;
@GetMapping("/{id}/courses")
public List<Course> getStudentCourses(@PathVariable("id") Long id){
return studentRepository.getStudentCourses(id);
}

我尝试了很多查询,但我得到了以下邮递员的回复:

[
{
"id": 1,
"title": "Machine Learning",
"abbreviation": "ML",
"modules": 12,
"fee": 1500.0,
"students": [
{
"id": 1,
"name": "John Doe",
"age": 15,
"grade": "8th",
"courses": [
{
"id": 1,
"title": "Machine Learning",
"abbreviation": "ML",
"modules": 12,
"fee": 1500.0,
"students": [
{
"id": 1,
"name": "John Doe",
"age": 15,
"grade": "8th",
"courses": [
{
.......

我猜我的问题有误,任何帮助都将不胜感激。

这可能是因为双向映射导致无限递归。您可以使用@JsonManagedReference@JsonBackReference与实体在您的情况下使用@JsonManagedReference与学生实体和@JsonBackReference与课程实体,当结果试图串行化时,该实体将防止循环

查询将类似于此

"select s.courses from Student s join s.courses where s.id = :id "

最新更新