从映射表中检索数据

时间:2018-05-16 13:43:47

标签: hibernate hql

我有两个有多对多关系的实体:

之间的连接表

Student.java:

@ManyToMany
    @JoinTable(name="STUDENT_TEACHER", joinColumns=@JoinColumn(name="STUDENT_ID"), inverseJoinColumns=@JoinColumn(name="TEACHER_ID"))

    private Collection<Teacher> teachers = new ArrayList<Teacher>();

Teacher.java:

@ManyToMany
private Collection<Student> students= new ArrayList<Student>();

我使用条件来检索所有学生:

studentList = session.createCriteria(Student.class).list();

但是现在我想要一个Teacher id=2下的学生列表,而映射表STUDENT_TEACHER不是类,在这种情况下如何检索?

1 个答案:

答案 0 :(得分:0)

您可以触发HQL,例如,

SELECT s FROM Student s WHERE s.teachers.id = 2

此外,您的Teacher类中不存在many to many关系的反面。它应该用下面的代码注释:

@ManyToMany(mappedBy="teachers")
private Collection<Student> students= new ArrayList<Student>();