Sleep using another object

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 created objects for User, Course, and Student objects and set the following mappings:

User   -> Course  - one to many
Course -> Student - many to many

In my Java classes, I can access the user's courses by calling user.getCourses(), and I can access all the students in the course by calling course.getStudents(). I want to find all the students in all courses taught by a particular user , for example user.getCourse().getStudents(), but since user.getCourses()returns Collection<Course>, I cannot call course.getStudents()to the Collection. How do I implement this with Hibernate? Is a named query my only option?

+3
3

, fetchType = EAGER , HQL .

+1

:

List<Student> students = new ArrayList<Student>();
for ( Course course : user.getCourses() )
{
    students.addAll( course.getStudents() );
}

(. SELECT N + 1"

, : "SELECT c.students FROM Course c WHERE c.user.name = 'username'"

0

, ,

HQL

SELECT DISTINCT _student FROM User AS _user, IN ( _user.courses ) _course, IN( _course.students ) _student WHERE _user.id = :id

SELECT DISTINCT _student FROM User _user inner join _user.courses _course inner join _course.students _student WHERE _user.id = :id

,

0

Source: https://habr.com/ru/post/1732113/


All Articles