Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering a join fetched collection in JPA using JPQL/HQL

Tags:

java

jpa

hql

jpql

Given the below JPQL statement, how do I modify it so that the kittens in the resulting list are ordered by their age property?

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

I've tried multiple approches but without any luck. This is esentially what I would like to do, but it doesn't work:

SELECT c FROM Cat c left join fetch c.kittens k WHERE c.id = :id ORDER BY k.age
like image 243
stuff22 Avatar asked May 05 '11 20:05

stuff22


People also ask

Can JPQL join operations?

We can also join multiple entities in a single JPQL query: @Test public void whenMultipleEntitiesAreListedWithJoin_ThenCreatesMultipleJoins() { TypedQuery<Phone> query = entityManager.

What is fetch in HQL?

A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.

Is JPQL and Hql same?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.


2 Answers

Hej,

I don't think this is possible when applied using queries. But as far as I remember, you can use this to add default ordering to your collection in the mapping:

@OrderBy("myColumName asc")
like image 90
bigZee77 Avatar answered Oct 05 '22 00:10

bigZee77


In addition to @bigZee77's answer, you could also perhaps change your query and query for the kitten instead of the cat. The resulting list of kittens would be ordered, and every kitten would 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 doesn't have any kitten, you would get an empty list, though.

The alternative is of course to provide a Java method which sorts the list of kittens.

like image 23
JB Nizet Avatar answered Oct 04 '22 22:10

JB Nizet