HQL order by within a collection
Question
I have 2 entities: car and wheels (oneToMany) and I want to retrieve my car, with all the wheels and (this is the tricky part) ordered by wheels.location. The below code throws an exception with the message "illegal attempt to dereference collection."
Select c
from Car
LEFT JOIN FETCH c.wheels
order by c.wheels.location
Any idea how to do this and if this is possible in HQL?
Solution
SELECT DISTINCT c
FROM Car
LEFT JOIN FETCH c.wheels AS wheels
ORDER BY wheels.location
OTHER TIPS
I think that you have to set the Car alias in the from request:
SELECT DISTINCT c
FROM Car c
LEFT JOIN FETCH c.wheels AS wheels
ORDER BY wheels.location
Below is an excerpt from the Hibernate documentation on hql ordering:
select cat from Cat cat
join cat.kittens kitten
group by cat.id, cat.name, cat.other, cat.properties
having avg(kitten.weight) > 100
order by count(kitten) asc, sum(kitten.weight) desc
Hmm. Think you might need to use an alias?
Select c from Car
LEFT JOIN FETCH c.wheels wheel
order by wheel.location
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow