无需初始化的休眠计数集合大小 [英] Hibernate count collection size without initializing
问题描述
有没有一种方法可以在不初始化的情况下计算关联集合的大小?
Is there a way I can count the size of an associated collection without initializing?
例如
Select count(p.children) from Parent p
(我不能以任何其他方式执行此操作是有充分理由的,因为我的 where 子句更复杂,而我的 from 子句是多态查询)
(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)
谢谢.
推荐答案
除了查询之外的一个可能的解决方案可能是将 children
与 lazy="extra"
映射(在 XML 中)符号).通过这种方式,您可以使用您需要的任何查询获取 Parent,然后调用 parent.getChildren().size()
而不加载整个集合(只有 SELECT COUNT
类型查询被执行).
A possible solution other than queries might be mapping children
with lazy="extra"
(in XML notation). This way, you can fetch the Parent with whatever query you need, then call parent.getChildren().size()
without loading the whole collection (only a SELECT COUNT
type query is executed).
如果有注释,那就是
@OneToMany
@org.hibernate.annotations.LazyCollection(
org.hibernate.annotations.LazyCollectionOption.EXTRA
)
private Set<Child> children = new HashSet<Child>();
更新:引自 Java Persistence with Hibernate,ch.13.1.3:
Update: Quote from Java Persistence with Hibernate, ch. 13.1.3:
如果调用任何不是标识符 getter 的方法,则代理将被初始化方法,如果您开始迭代其元素或如果您可以调用任何集合管理操作,例如 size()
和 contains()
.Hibernate 提供了一个额外的设置,对于大型集合最有用;它们可以被映射为额外懒惰.[...]
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. [...]
[映射如上,]如果调用 size()
、contains()
或 isEmpty()
,则集合不再初始化> — 查询数据库以检索必要的信息.如果是 Map
或 List
,则操作 containsKey()
而get()
也直接查询数据库.
[Mapped as above,] the collection is no longer initialized if you call size()
, contains()
, or isEmpty()
— the database is queried to retrieve the necessary information. If it’s a Map
or a List
, the operations containsKey()
and get()
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
这篇关于无需初始化的休眠计数集合大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!