Search code examples
hibernatehql

HQL Syntax to retrieve from a manytomany relationship


I have two entities, Student and Teacher who have relationship many to many

Student.java:

@ManyToMany
    @JoinTable(name="CROOS_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'm currently trying to retrieve a list of sudents that are under a specific teacher useing the teacher's id like

select a from Student JOIN a.teachers p FROM Teacher where p.id = :id

and gave me an error

Ia also changed a little like removed FROM Teacher but it still doesn't work, any other way I could do?


Solution

  • The correct one should be:

    select a from Student a JOIN a.teachers p where p.id = :id
    

    Your query contains some syntax flaw like:

    • Two from keyword inside single query

    • You did not specify alias for Student but use a