Search code examples
hibernatehql

retrieving data from a mapping table


I have two entities that have many to many relationship:

and a join table in between

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>();

I use criteria to retrieve all students like:

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

But now I want a list of students who are under Teacher id=2, while the mapping table STUDENT_TEACHER is not class, how can it be retrieved in this case?


Solution

  • You can fire an HQL, like,

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

    Also, inverse side of the many to many relationship is not present in your Teacher class. It should be annotated with below code:

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