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.”
By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.
Immediate fetching: an association, collection or attribute is fetched immediately when the owner is loaded. Lazy collection fetching: a collection is fetched when the application invokes an operation upon that collection. This is the default for collections.
The FetchType. LAZY tells Hibernate to only fetch the related entities from the database when you use the relationship. This is a good idea in general because there's no reason to select entities you don't need for your uses case. You can see an example of a lazily fetched relationship in the following code snippets.
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) .list();
Use fetch profiles: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/performance.html#performance-fetching-profiles
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With