Consider this simple database schema:
User Course StudentCourse Student
+-------------+ +-------------+ +-------------+ +-------------+
| -user_id |1 *| -course_id |1 *| -course_id |* 1| -student_id |
| |---->| -user_id |---->| -student_id |---->| |
+-------------+ +-------------+ +-------------+ +-------------+
[1 *] = 1 to many relationship
I have created entities for the User, Course, and Student objects, and set up the following mappings:
User -> Course - one to many
Course -> Student - many to many
In my Java classes I can access the Courses of a User by calling user.getCourses()
and I can access all the Students in a Course by calling course.getStudents()
. I want to be able to find all of the Students in all of the Courses taught by a specific User like user.getCourse().getStudents()
, but because user.getCourses()
returns Collection<Course>
I cannot call course.getStudents()
on the Collection. How should I implement this with Hibernate? Is a named query my only option?