java 使用 JPQL/HQL 在 JPA 中订购连接提取的集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5903774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ordering a join fetched collection in JPA using JPQL/HQL
提问by stuff22
Given the below JPQL statement, how do I modify it so that the kittens in the resulting list are ordered by their age
property?
鉴于以下 JPQL 语句,我该如何修改它以便结果列表中的小猫按其age
属性排序?
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
采纳答案by bigZee77
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")
回答by JB Nizet
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:
除了@bigZee77 的回答之外,您还可以更改查询并查询小猫而不是猫。生成的小猫列表将被排序,每只小猫都将指向同一只猫:
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.
替代方法当然是提供一个 Java 方法来对小猫列表进行排序。