有没有一种方法可以在不初始化的情况下计算关联集合的大小?
例如
Select count(p.children) from Parent p
(我不能以任何其他方式这样做是有充分理由的,因为我的 where 子句更复杂,而我的 from 子句是一个多态查询)
谢谢。
最佳答案
查询以外的可能解决方案可能是将 children
映射到 lazy="extra"
(以 XML 表示法)。这样,您可以使用所需的任何查询来获取 Parent,然后调用 parent.getChildren().size()
而不加载整个集合(只有 SELECT COUNT
类型查询被执行)。
有了注释,就可以了
@OneToMany
@org.hibernate.annotations.LazyCollection(
org.hibernate.annotations.LazyCollectionOption.EXTRA
)
private Set<Child> children = new HashSet<Child>();
更新:引自 Java Persistence with Hibernate , channel 。 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.
因此,使用如上映射的实体,您可以这样做
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
关于java - hibernate 计数集合大小而不初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2913160/