Example & Tutorial understanding programming in easy ways.

What is Lazy fetching in Hibernate?

Lazy fetching in Hibernate: Lazy fetching always decides whether to load child objects while loading the Parent Object. We need to do some setting in 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


This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object .But in some cases need to load the child objects when parent is loaded. 


Just make the lazy=false and hibernate will load the child when parent is loaded from the database. 


Example : 


If TABLE ? EMPLOYEE mapped to Employee object and contains set of Address objects. 

Parent Class : Employee class 

Child class : Address Class 

public class Employee { 

private Set address = new HashSet(); // contains set of child Address objects 

public Set getAddress () { 

return address; 

public void setAddresss(Set address) { 

this. address = address; 


In the Employee.hbm.xml file 


<set name="address" inverse="true" cascade="delete" lazy="false"> 

<key column="a_id" /> 

<one-to-many class="beans Address"/> 

</set> 


In the above configuration


If lazy="false" : - when load the Employee object that time child object Address is also loaded and set to setAddress() method. If call employe.getAddress() then loaded data returns.No fresh database call. 


If lazy="true" :- This the default configuration. don?t mention then hibernate consider lazy=true. 


when load the Employee object that time child object Address is not loaded. So need extra call to data base to get address objects. 


If call employee.getAddress() then that time database query fires and return results. Fresh database call. 

Read More →