3

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

4 Answers 4

9

Take a look at extra-lazy collections

But if you need specific items, just query for them rather than taking them from a collection.

Sign up to request clarification or add additional context in comments.

1 Comment

So, normally, it would just retrieve the whole collection from the DB, right?
6

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();

Comments

1
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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.