在JPA查询中排序返回Child对象 [英] Ordering return of Child objects in JPA query

查看:130
本文介绍了在JPA查询中排序返回Child对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果我的JPA查询是这样的:
从父p中选择不同的p左边的连接fetch p.children order by p.someProperty

我正确得到由p.someProperty命令返回的结果,并且我正确地获取我热切地提取和填充的p.children集合。但我希望我的查询类似按p.someProperty,p.children.someChildProperty排序,以便在每个父对象内部填充的集合由someChildProperty进行子命令。



当我想到这些调用实际生成的sql时,这看起来很直观,但当我试图映射回层次结构对象时,我猜测它更少。

解决方案

为了保持顺序,请使用 TreeSet 。至于在父代中对集合进行排序,只需在代码中使用 Comparator



那么,请在您的父实体类的集合定义中尝试此操作。我希望你明白我的意思。



你可以使用这个JPA注解,

  @ javax.persistence.OrderBy(value =fieldName)

或者这个Hibernate特定的,

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

你也可以使用这个,

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

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

在比较器的情况下,必须有一个比较器。其他可能只适用于String集合。


So if my JPA query is like this: 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.

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.

解决方案

For preserving order, use TreeSet. As far as, sorting of a collection inside parent is concerned, just do it in your code using 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,

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

or this Hibernate specific,

@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.

这篇关于在JPA查询中排序返回Child对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆