Order a collection compiled in JPA using JPQL / HQL

Given the JPQL statement below, how can I change it so that the kittens in the resulting list are sorted by the age property?

 SELECT c FROM Cat c left join fetch c.kittens WHERE c.id = :id 

I tried a few matches, but no luck. This is essentially what I would like to do, but it does not work:

 SELECT c FROM Cat c left join fetch c.kittens k WHERE c.id = :id ORDER BY k.age 
+8
java jpa hql jpql
source share
2 answers

Hey

I do not think that this is possible when applied using queries. But as far as I remember, you can use this to add a default order to your collection when displaying:

 @OrderBy("myColumName asc") 
+9
source share

In addition to @ bigZee77's answer, you can also change your request and the request for a kitten instead of a cat. The resulting list of kittens will be ordered, and each kitten will point to the same cat:

 select k from Cat c inner join fetch c.kittens k where c.id = :id order by k.age 

If the cat does not have a kitten, you will receive an empty list.

An alternative, of course, is the Java method, sorting the list of kittens.

+3
source share

All Articles