我有一个使用Hibernate 3.6来执行持久性的Java-SE 1.6 / JPA应用程序。这样的应用程序具有如下所示的域模型(以简化形式):
@Entity
@Table(name = "students")
public class Student implements Serializable {
// many fields, getters and setters
@OneToMany(mappedBy="student", cascade=CascadeType.ALL)
private List<Enrollment> enrollments = new ArrayList<Enrollment>();
public Collection<Enrollment> getEnrollments() {
return Collections.unmodifiableCollection(enrollments);
}
}
@Entity
@Table(name = "enrollments")
public class Enrollment implements Serializable {
// many fields, getters and setters
@ManyToOne
private Student student;
public Student getStudent() {
return student;
}
@OneToOne
private Course course;
public Course getCourse() {
return course;
}
}
@Entity
@Table(name = "courses")
public class Course implements Serializable {
// many fields, getters and setters
}
因此,用简单的英语,这个模型使我们能够建模以下域规则:
“某位学生可同时参加多门课程。”
到目前为止,一切都在顺利运作。这里的问题是:
“如何选择在指定课程中注册的所有学生?”
所以,我有Course
的实例,我的工作是选择与Student
(间接)相关的Course
的所有实例(通过{{1}的实例通过使用Hibernate查询。
有人可以给我一些意见和/或想法吗?
提前致谢。
答案 0 :(得分:1)
试试这个
select s from Student s join s.enrollments e join e.course c where c.id = :courseId
使用标准
List<Student> students = session.createCriteria(Student.class).createAlias("enrollments", "e").createAlias("e.course", "c").add(Restrictions.eq("c.id", courseId)).list();