Take the 2-minute tour ×

i saw following statement in book "hibernate in action". anyone can tell me how to override strategy at runtime. and can you do opposite way that is i have fetching strategy set lazy as false and i want to set it true?

“Lazy fetching lets you decide how much of the object graph is loaded in the first database hit and which associations should be loaded only when they’re first accessed. Lazy fetching is a foundational concept in object persistence and the first step to attaining acceptable performance. We recommend that, to start with, all associations be configured for lazy (or perhaps batched lazy) fetching in the mapping file. This strategy may then be overridden at runtime by queries that force eager fetching to occur.”

share|improve this question

3 Answers 3

If you're using HQL for your queries, you can specify your eager fetching using the "fetch" keyword, like so:

from Cat as cat
    inner join fetch cat.mate
    left join fetch cat.kittens child
    left join fetch child.kittens

If you're using the Criteria Query API, you can specify the fetch mode using setFetchMode

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "Fritz%") )
    .setFetchMode("mate", FetchMode.EAGER)
    .setFetchMode("kittens", FetchMode.EAGER)
share|improve this answer
It appears that Hibernate isn't happy with having a 'left join fetch' added unless the target entity appears in the select list when using JPA2 criteria. It produces the error "query specified join fetching, but the owner of the fetched association was not present in the select list" if a root.fetch("someChildProperty") is added to request a left join fetch. Ideas? JPA2 seems to make it amazingly hard to say "fetch this lazily most of the time, but eagerly in this one situaton". –  Craig Ringer Jun 20 '12 at 8:55
Thank you very much! Highly appreciated, Andrew! –  Michael Simons Apr 9 at 10:46

Use fetch profiles: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/performance.html#performance-fetching-profiles

share|improve this answer
It seems you can use fetch profiles to override "select" with "join", but not vice-versa. –  David May 8 at 20:21

For the eager query you may write something like this using LINQ provider:

List<Customer> customers = session.Query<Customer>().Fetch(c => c.Orders).ToList();

This fills all the Orders for all fetched Customers in one SQL query:

    customer0_.CustomerId   as CustomerId0_0_,
    customer0_.ContactName  as ContactN3_0_0_,
    orders1_.CustomerId     as CustomerId0__,
    orders1_.OrderId        as OrderId0__
    orders1_.OrderDate      as OrderDate3_1_,
from   Customers customer0_
   left outer join Orders orders1_
     on customer0_.CustomerId = orders1_.CustomerId

You can fetch grandchild collections too (see here).

share|improve this answer

Your Answer


