Reputation: 632
I have 4 entities:
User
, Teacher
, Student
, Course
and 4 tables:
t_user, t_teacher_course, t_student_course, t_course
Teacher
and Student
extends User
(with descriminators) and have @ManyToMany
relationship with Course
(User
do NOT have)
Teacher
's relations stored in t_teacher_course
and Student
's relations stored in t_student_course
.
Now i want to select all users with courses (if they exists) in one query
select u from User u left join fetch u.courses c
(notice that User do not have courses)
This select generated something like this:
select
...
from
T_USER user0_
left outer join
T_TEACHER_COURSE course1_
on user0_.USERID_=courses1_.TEACHER_
left outer join
T_COURSE course2_
on courses1_.LANE_=course2_.COURSENAME_
where
user0_.GROUP_=?
As you can see clearly Hibernate did NOT join with t_student_course table
I am using Hibernate 4.1Final
Question: Does Hibernate support such queries
a) if supports then why it didn't fetched courses for Student
entity?
b) if do not support than how can i select all users with their courses using JPQL?
Upvotes: 1
Views: 544
Reputation: 692281
Since u.courses
could be student.courses
or teacher.courses
, Hibernate resolves the ambiguity by choosing the first (or last) association with this name in its metadata.
It might work if the name of the courses
collection is not the same in both subclasses. For example, you could define Student.attendedCourses
and Teacher.teachedCourses
.
Otherwise, you'll have to issue two queries (one for teachers and one for students), and join the result lists. Or you'll have to pull up the association in the User entity.
Upvotes: 2