简体   繁体   English

Hibernate 中的延迟加载和 collections

[英]Lazy loading and collections in Hibernate

If I want to fetch a single, or just a small number of items (for instance, the 1st, the 3rd, and the 5th) from a lazy loaded collection, will Hibernate fetch all items from the DB, and then return the ones I request, or it will specifically retrieve only the requested ones from the DB如果我想从延迟加载的集合中获取单个或少量项目(例如,第一个、第三个和第五个),Hibernate 会从数据库中获取所有项目,然后返回我请求,或者它将专门从数据库中仅检索请求的请求

Take a look at extra-lazy collections看看超懒 collections

But if you need specific items, just query for them rather than taking them from a collection.但是,如果您需要特定项目,只需查询它们而不是从集合中获取它们。

An alternative to extra lazy is to use Collection filters http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#objectstate-filtering额外懒惰的替代方法是使用 Collection 过滤器http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#objectstate-filtering

This is basically a query based on the content of a collection.这基本上是基于集合内容的查询。 And that includes pagination possibilities.这包括分页的可能性。

Collection tenKittens = session.createFilter(
    mother.getKittens(), "")
    .setFirstResult(0).setMaxResults(10)
    .list();
In hibernate, pagination doesn't work well when eagerly fetching a collection. 

In this case, hibernate fetch all the table data without pagination and apply an memory pagination inside the JVM.在这种情况下,hibernate 获取所有表数据而不进行分页,并在 JVM 内应用 memory 分页。 This warn is printed when it occurs: {code:java} [/api] WARN ohhiast.QueryTranslatorImpl - HHH000104: firstResult/maxResults specified with collection fetch;发生此警告时会打印:{code:java} [/api] WARN ohhiast.QueryTranslatorImpl - HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!在内存中应用! {code} {代码}

We should at least propose a pull request to optionnally throw a RuntimeException for those cases.对于这些情况,我们至少应该提出一个拉取请求,以选择性地抛出 RuntimeException。

I think you have few possibilities.我认为你的可能性很小。 You may bound your results with starting element a number of elements to fetch (like with pagination).您可以将结果与要获取的起始元素绑定(例如分页)。 You may also write an appropriate SQL query instead of using HQL or criteria.您也可以编写适当的 SQL 查询,而不是使用 HQL 或条件。 If you use extra lazy collection, Hibernate will probably execute a query for each time you get an element from the list.如果您使用额外的惰性收集,Hibernate 可能会在您每次从列表中获取一个元素时执行一个查询。 So effectiveness of each solution strictly depends on your application and amount of data you have in a database.因此,每个解决方案的有效性严格取决于您的应用程序和数据库中的数据量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM