Hibernate在不初始化的情况下计算收集大小 [英] Hibernate count collection size without initializing
问题描述
有没有一种方法可以在不初始化的情况下计算关联集合的大小?
eg
从父母中选择count(p.children)p
是一个很好的理由,为什么我不能做任何其他方式,因为我的where子句更复杂,我的from子句是多态查询)
谢谢。
除查询以外的可能解决方案可能会将 children
与 lazy =extra
(以XML表示法)。这样,您可以使用您需要的任何查询来获取Parent,然后在不加载整个集合的情况下调用 parent.getChildren()。size()
(仅限于执行SELECT COUNT
类型查询)。
使用注释,它会是
(
org.hibernate.annotations.LazyCollectionOption.EXTRA
)
私人的设置<儿童> children = new HashSet< Child>();
更新:来自 Java Persistence with Hibernate ,ch。 13.1.3:
如果您调用任何不是标识符getter
方法的方法,则会初始化代理,如果开始迭代其元素,或者如果
调用任何集合管理操作(例如size()
和),则初始化()
。
Hibernate提供了一个对大型集合最有用的额外设置;它们可以被映射为额外的懒惰。 [b]
$ b [p] [映射如上]如果调用size()
,contains()
或isEmpty()
- 查询数据库以检索必要的信息。如果它是一个Map
或一个List
,操作containsKey()$ c $
get()
也直接查询数据库。因此,对于如上所示映射的实体,您可以执行
父级p = //执行查询以加载所需的父级
//由于延迟加载,此时p.children是一个代理对象
int count = p.getChildren()。size(); //这个集合没有加载,只有它的大小
Is there a way I can count the size of an associated collection without initializing?
e.g.
Select count(p.children) from Parent p
(there is a good reason why I cant do this any other way as my where clause is more complicated and my from clause is a polymorphic query)
Thanks.
解决方案A possible solution other than queries might be mapping
children
withlazy="extra"
(in XML notation). This way, you can fetch the Parent with whatever query you need, then callparent.getChildren().size()
without loading the whole collection (only aSELECT COUNT
type query is executed).With annotations, it would be
@OneToMany @org.hibernate.annotations.LazyCollection( org.hibernate.annotations.LazyCollectionOption.EXTRA ) private Set<Child> children = new HashSet<Child>();
Update: Quote from Java Persistence with Hibernate, ch. 13.1.3:
A proxy is initialized if you call any method that is not the identifier getter method, a collection is initialized if you start iterating through its elements or if you call any of the collection-management operations, such as
size()
andcontains()
. Hibernate provides an additional setting that is mostly useful for large collections; they can be mapped as extra lazy. [...][Mapped as above,] the collection is no longer initialized if you call
size()
,contains()
, orisEmpty()
— the database is queried to retrieve the necessary information. If it’s aMap
or aList
, the operationscontainsKey()
andget()
also query the database directly.So with an entity mapped as above, you can then do
Parent p = // execute query to load desired parent // due to lazy loading, at this point p.children is a proxy object int count = p.getChildren().size(); // the collection is not loaded, only its size
这篇关于Hibernate在不初始化的情况下计算收集大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!