java JPA查询中子对象的排序返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/408051/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:16:35  来源:igfitidea点击:

Ordering return of Child objects in JPA query

javahibernatejpa

提问by Brian Deacon

So if my JPA query is like this: Select distinct p from Parent p left join fetch p.children order by p.someProperty

所以如果我的 JPA 查询是这样的: Select distinct p from Parent p left join fetch p.children order by p.someProperty

I correctly get results back ordered by p.someProperty, and I correctly get my p.children collection eagerly fetched and populated. But I'd like to have my query be something like "order by p.someProperty, p.children.someChildProperty" so that the collection populated inside each parent object was sub-ordered by someChildProperty.

我正确地得到了由 p.someProperty 排序的结果,并且我正确地得到了我的 p.children 集合急切地获取和填充。但我希望我的查询类似于“按 p.someProperty、p.children.someChildProperty 排序”,以便填充在每个父对象内的集合由 someChildProperty 进行子排序。

This seems intuitive when I think in terms of the sql that is actually generated for these calls, but I guess less so when it tries to map back to hierarchical objects.

当我考虑为这些调用实际生成的 sql 时,这似乎很直观,但是当它尝试映射回分层对象时,我猜不那么直观。

回答by Adeel Ansari

For preserving order, use TreeSet. As far as, sorting of a collection inside parent is concerned, just do it in your code using Comparator.

为了保持顺序,请使用TreeSet。就父级内部集合的排序而言,只需在您的代码中使用Comparator 即可

Well, try this on your collection definition in your parent entity class. I hope you are getting my point.

好吧,在您的父实体类中的集合定义上试试这个。我希望你明白我的意思。

You can use this JPA annotation,

您可以使用此 JPA 注释,

@javax.persistence.OrderBy(value = "fieldName")

or this Hibernate specific,

或者这个 Hibernate 特定的,

@org.hibernate.annotations.OrderBy(clause = "FIELD_NAME asc")

and you can also use this,

你也可以使用这个,

@org.hibernate.annotations.Sort(type = SortType.NATURAL)

or

或者

@org.hibernate.annotations.Sort(type = SortType.COMPARATOR)

In the case of comparator, a comparator must be in place. Other might only work with String collections.

如果是比较器,则必须有比较器。其他可能只适用于字符串集合。

回答by cliff.meyers

Adeel basically has this nailed. You can also use those with a List which might be important if your collections contain the same entity more than once.

Adeel 基本上已经解决了这个问题。您还可以将那些与 List 一起使用,如果您的集合多次包含相同的实体,这可能很重要。