java - hibernate 计数集合大小而不初始化

标签 java hibernate lazy-loading

有没有一种方法可以在不初始化的情况下计算关联集合的大小?

例如

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() and contains(). 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(), 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.

因此,使用如上映射的实体,您可以这样做

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/

相关文章:

java - AlarmManager 有时会延迟触发,或者根本不触发

java - 如何在基类中包含属性文件然后调用其他类?

java - 在 Apache Tomcat 服务器上部署 GWT 应用程序时出现 500 内部服务器错误

angular - 延迟加载在 prod 构建 Angular 8 上被破坏

java - 批量加载延迟加载的 Hibernate 属性

java - 带 UiBinder 的 GWT LazyPanel

java - 如何从 process.getErrorStream() 获取消息

hibernate - 什么是 hibernate 中的上下文 session ?

java - 调用entityManager.find()是否需要EntityTransaction?

sql - HQL查询以检查集合的大小是否为0或为空