Ordering a join fetched collection in JPA using JPQL/HQL

烂漫一生 提交于 2019-12-09 09:40:12

问题


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

回答1:


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")



回答2:


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.



来源:https://stackoverflow.com/questions/5903774/ordering-a-join-fetched-collection-in-jpa-using-jpql-hql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!