我有 3 个表:Student、Course 和 Student_Course。每个学生可能有几门课程,每门课程可能有几个学生。(多对多)。我需要编写一种方法来获得课程的所有学生。在 SQL 中,它是 2 个内部连接。我试过这个:
Criteria criteria = session.createCriteria(Student.class, "s");
criteria.createAlias("student_course", "s_c");
criteria.createAlias("course", "c");
criteria.add(Restrictions.eq("s.student_id", "s_c.student_id"));
criteria.add(Restrictions.eq("s_c.course_id", "c.course_id"));
criteria.add(Restrictions.eq("c.course_id", course.getId()));
courses = criteria.list();
但我得到一个org.hibernate.QueryException: could not resolve property: student_course of: com.example.entity.Student
@Entity
@Table(name = "STUDENT")
public class Student {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STUDENT_ID", unique = true, nullable = false)
private long id;
@ManyToMany(targetEntity = Course.class, fetch = FetchType.EAGER)
@JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name = "student_id") }, inverseJoinColumns = { @JoinColumn(name = "course_id") })
private Set<Course> courses = new HashSet<Course>();
和:
@Entity
@Table(name = "COURSE")
public class Course{
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "COURSE_ID", unique = true, nullable = false)
private long id;
如何编写正确的代码?