Saturday, 9 February 2013

What is lazy loading in Hibernate?


Lazy loading means that all associated entities and collections aren't initialized if you load an entity object.


you have a parent and that parent has a collection of children. 

Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. 

Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, 

hibernate will load them automatically when you try to access a child. 

Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded.


Also . Hibernate will not actually load all children when you access the collection. 
Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. 
In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().
  • This feature is enabled by default in Hibernate.
  • This feature can be set on the level of one-to-one or one-to-many relations.



How To Set it false?

It can be disabled by setting the attribute lazy = “false” in the mapping file
<class name=“Parent" table=“Student">
     <set name="children“ lazy=“false“>
          <key column=“parent_ID"/>
           <one-to-many class=“Subject"/>
      </set>
</class>
  • By default / if the lazy attribute set to “true” and if the object is detached( when the session is closed)
    • calling Parent.getSubjects() will throw an Exception
    • If in the object is still in the persistence state ,calling the previous method will hit the DB and retrieve the list of Parent

  • If the lazy attribute set to “false” when retrieving the Parent’s data
    • it will retrieve the list of subjects as well
    • So calling the previous method will return the list of subjects whether in the persisted or detached mood.



No comments:

Post a Comment