If I want to fetch a single, or just a small number of ite开发者_StackOverflowms (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
Take a look at extra-lazy 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
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. This warn is printed when it occurs: {code:java} [/api] WARN o.h.h.i.ast.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.
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. If you use extra lazy collection, Hibernate will probably execute a query for each time you get an element from the list. So effectiveness of each solution strictly depends on your application and amount of data you have in a database.
精彩评论