我有三个实体类; Student
,Subject
和StudentSubject
。
Student
在StudentSubject
上有一对多关系,而Subject
在StudentSubject
上也有一对多关系。
学生班
@Entity
@Getter
@Setter
public class Student {
@Id
private String email;
@OneToMany(mappedBy = "student")
@JsonManagedReference
private List<StudentSubject> subjects;
//more elements
}
主题类
@Entity
@Getter
@Setter
public class Subject {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JsonBackReference
private Teacher teacher;
@OneToMany(mappedBy = "student")
@JsonManagedReference
private List<StudentSubject> students;
//more elements
}
StudentSubject类
@Entity
@IdClass(StudentSubjectId.class)
@Getter
@Setter
public class StudentSubject implements Serializable {
//Primary keys
@Id
@Column(name = "subject_id")
Long subjectId;
@Id
@Column(name = "student_email")
String studentEmail;
String uid;
@ManyToOne
@JsonBackReference
@JoinColumn(name = "subject_id", insertable = false, updatable = false)
private Subject subject;
@ManyToOne
@JsonBackReference
@JoinColumn(name = "student_email", insertable = false, updatable = false)
private Student student;
}
我有3个班级,而不是2个班级,因为每个学生科目对都有特定的属性。因此这种安排。
当我从存储库中读取主题时,
Subject subject = subjectRepository.findByNameAndTeacher(subjectName, teacher);
subject.getStudents();
除了学生名单外,所有细节都是正确的。它总是空的。(通过添加断点来检查)
Hibernate / JPA执行的查询是
获得主题(?)
select
subject0_.id as id1_3_,
subject0_.name as name2_3_,
subject0_.teacher_email as teacher_3_3_
from
subject subject0_
left outer join
teacher teacher1_
on subject0_.teacher_email = teacher1_.email
where
subject0_.name =?
and teacher1_.email =?
选择学生列表(?)
select
students0_.student_email as student_1_2_0_,
students0_.subject_id as subject_2_2_0_,
students0_.student_email as student_1_2_1_,
students0_.subject_id as subject_2_2_1_,
students0_.uid as uid3_2_1_,
subject1_.id as id1_3_2_,
subject1_.name as name2_3_2_,
subject1_.teacher_email as teacher_3_3_2_,
teacher2_.email as email1_5_3_,
teacher2_.name as name2_5_3_
from
student_subject students0_
left outer join
subject subject1_
on students0_.subject_id = subject1_.id
left outer join
teacher teacher2_
on subject1_.teacher_email = teacher2_.email
where
students0_.student_email =?
等等。
我认为这里的问题是最后一个where子句被错误地添加,并且表中的公共属性不会显示一次。我该如何解决这个问题?
答案 0 :(得分:1)
您的地图有拼写错误。在Subject
类中,它应该是@OneToMany(mappedBy = "subject")
而不是mappedBy="student"
因此你的错误的where子句。
这就是它使用的原因
where students0_.student_email =?
代替
where students0_.subject_id =?
因为它认为从主题获取学生的方式是通过student_email
列,如您的映射所示。
答案 1 :(得分:0)
您尚未指定提取类型。这应该解决它。
@OneToMany(mappedBy = "student", fetch = FetchType.EAGER)
@JsonManagedReference
private List<StudentSubject> students;