Monday, August 1, 2016

Hibernate – fetching strategies



Hibernate has few fetching strategies to optimize the Hibernate generated select statement, so that it can be as efficient as possible. The fetching strategy is declared in the mapping relationship to define how Hibernate fetch its related collections and entities.

Fetching Strategies

There are four fetching strategies

fetching="join" -> Disable the lazy loading, always load all the collections and entities, if you do fetching="join" it will retrieve all the information in a single select statement.

To solve n+1 select problem for n queries (parent child relationship) in hibernate we use fetch="join" instead of fetch="select”. Lazy setting decides whether to load child objects while loading the Parent Object. You need to do this setting respective hibernate mapping file of the parent class. Lazy = true (means not to load child) By default the lazy loading of the child objects is true.

fetching="select" (default) = Lazy load all the collections and entities.

batch-size=" N" = Fetching up to ‘N’ collections or entities, *Not record*.
fetch-"subselect" = Group its collection into a sub select statement.


Difference between Eager Initialization Lazy Initialization

LAZY = fetch when needed
EAGER = fetch immediately

Eager Initialization Lazy Initialization
To increase the performance while retrieving records from a database table, Hibernate uses two styles – Eager Initialization and Lazy Initialization. Concept-wise, a good programming practice is lazy initialization; but both have their own importance in coding.

In eager initialization, the object is created in the program execution, in a normal way, which sometimes the programmer may not use it in the program. This looks waste of memory and processor time.

Other way is to create the object when the programmer really requires. This is called lazy initialization (one of the design patterns). That is, if the object is created at runtime, only when the programmer requires is known as lazy initialization. So, which is preferred, definitely you say lazy initialization. Lazy initialization is basically meant for improving the performance by avoiding unnecessary computation (load on the microprocessor) and reducing memory requirements.

  



No comments:

Post a Comment