Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to override hibernate fetching strategy at runtime

Tags:

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

like image 932
Tsung Lin Tsai Avatar asked Mar 25 '11 16:03

Tsung Lin Tsai


People also ask

What is the default fetching strategy in Hibernate?

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.

What are the two types of fetch strategies?

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.

What is the use of fetch mode lazy in Hibernate criteria?

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.


2 Answers

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(); 
like image 115
Andrew Newdigate Avatar answered Sep 18 '22 08:09

Andrew Newdigate


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

like image 44
Emek Demir Avatar answered Sep 21 '22 08:09

Emek Demir