File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Object Relational Mapping and the fly likes what is lazy initialization  in hibernate Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "what is lazy initialization  in hibernate" Watch "what is lazy initialization  in hibernate" New topic
Author

what is lazy initialization in hibernate

Ajay Cheenath
Greenhorn

Joined: Jun 27, 2005
Posts: 7
I am very new to hibernate technology ,please help me to know what is what is lazy initialization in hibernate.And what is adv and disadvt. of using it.
Thanks in advance .
Ajay Cheenath.
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
i guess its something like this:
when loading an obj that has a collection, hibernate loads collection elements ONLY when actually you ask for them; so this improves performance, among other advantages


java amateur
Jack Wiesenthaler
Ranch Hand

Joined: Jul 26, 2001
Posts: 75
yep, lazy initialization improves performance by delaying the fetch from the database until the returned object is actually queried for the data...it works similar to write behind caching on your hard disk ;-)
Ronish Cheenath Raphael
Greenhorn

Joined: Jul 05, 2005
Posts: 11
Hi Ajay,

when u use hibernate u can make lazy=true or lazy=false.
I think this comes into play only when u deal with one to many or many to many relationships in database.

if u mentioned lazy=true

and u call from a company bean like

Collection x = company.getAllEmployees();

x will be empty;


if u mentioned lazy=false

x will contain the data as output of the getter funtion.


So if u put lazy=true then u need to write HQL quires for getting these kind of collections. else if lazy = false u can get the collection at rit time when u fecth the company object.


So taking performance(time cost and memeory cost) as criteria the its better to make lazy=true.

And if u want to do ur job fast and want to meet ur gul soon then dont hesitate put lazy=false and proceed....ha ha ha.

Regards,
-Ronish Cheenath
S Sudhindra
Greenhorn

Joined: Sep 26, 2004
Posts: 5
Hi all,
Is it lazy initialization or lazy instantiation? I think it should be the latter.
Thanks and regards,
Sudhindra
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Originally posted by S Sudhindra:
Hi all,
Is it lazy initialization or lazy instantiation? I think it should be the latter.
Thanks and regards,
Sudhindra


The Hibernate documentation uses the term "lazy initialization".


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Ajay Cheenath
Greenhorn

Joined: Jun 27, 2005
Posts: 7
Thanks Ronish and all.
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 9912
    
158

if u mentioned lazy=true

and u call from a company bean like

Collection x = company.getAllEmployees();

x will be empty;


Then how do we load the collection. Do we give a explicit call to load it from database?

As per my understanding, if lazy=true is specified, the collection will be loaded from database on giving a call to getAllEmployees(in the above example). So, as per my understanding, setting lazy=true, will NOT return an empty collection. The only difference between lazy=true and lazy=false, according to me is the time at which the data is loaded.

Please confirm

Thank you


[My Blog] [JavaRanch Journal]
Ronish Cheenath Raphael
Greenhorn

Joined: Jul 05, 2005
Posts: 11
Hi Jaikiran,

Yes theoreticaly ur rit am accepting the kick. But I dont think when v do a real project this facility can be used.

becas if lazy = true

Company company = ----DAO.getCompanyForID(12); // in common
// practice
// opening
// session and
// closing
// session
// included in
// in this
// function call
// due layering
// architecture.
Collection x = company.getAllEmployees();

In this case i think x will be empty.

But ur argument come into play when logic flows as folows

1. open session

2. company = getCompanyFunction();

3. Collection x=company.getAllEmployees();

4. Now x is not empty

5. close session.


But i think nobody will select a flow like this in even a mid sized project.

ie; ur comment will work only when the session remaining open.


But As I seen all projects using hibernate use some logic layering
were opensession and close session do imediatly in Data access function. So when u try to access tis kind of collections ..hibernate session will be closed. So when v access company.getAllEmps() it will give a empty collection as output.

So I am very sorry for the last short reply.

Thanks jaikiran for having a nice thought abt it...

if u have any doubts plz go through

http://jroller.com/page/kbaum/20040708


Regards,
-Ronish Cheenath Raphael
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 9912
    
158

Hi Ronish,
Thanks a lot, for explaining in detail, the lazy initialization concept in Hibernate. Ya you are right, normally in real-life projects, the session is closed, on the completion of the data access function. I was not aware that lazy=true would work only in case, of session being open. Thanks for explaining the same

-Jaikiran
Amit Sehgal
Greenhorn

Joined: Jul 24, 2006
Posts: 2
Thanks for your information about lazy=true and closed session problem. What is the best procedure for a layered architecture to use lazy=true.
I mean to get the related obecjt Set loaded only when it is required.

What is the best architechtural way to solve both issues i.e keeping lazy=true and getting the data whenever or whereever required, not considering the boundary of Open Sessions.
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 9912
    
158

See if this helps
Sanju
Greenhorn

Joined: Apr 10, 2006
Posts: 10
Hi All,

I think there is little bit confusion going on for lazy initialization. Though few explanations a good but missing some points.
Basically lazy initialization works like that.
1. If lazy = "true"
Any associated collection will not be loaded first time, for an example if Department is associated with Employee then on first loading of the Department entity, associated Employee entities will not be loaded.
Note: it will not be loaded even if you say
List list = department.getEmployees();
So in that case list will be always empty. Now once you do any operation on the list then only Employee entities will be loaded from DB, like list.size() etc.

How hibernate intercept the method calls on collection - They have their own implementation of List, Set etc.
2. Also note that you can not call department.getEmployees() and do operation on returned collection once session is closed and transaction is committed. So the Rule is if lazy="true" you can load associated collections lazily if and only if session is open.

Hope fully that will give you enough information.

Thanks
Sanjeev T
Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
Do not initialize untill its required.


Rahul Bhattacharjee
LinkedIn - Blog
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

Also to add to your guys discussion. If you lazy initialize a Collection and close the session before loading the Collection, then try to access the Collection you will get a LazyInitializationException thrown. This is the problem some people encounter when trying to access the Collection in a jsp page, and created the Session In View design pattern.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

It is lazy initialization, not instantiation.

It does have uses. For instance, if all you want is to get the name of an object, but do not want all its children to be loaded, then lazy initialization will spare you that load.

But you should not think of it in terms of lazy population of some GUI or otherwise. It can not be used in that way. Its lazy within a session, not without the session. In other words, just because hibernate is lazy, does not automatically give your application laziness.
shehroze sha
Greenhorn

Joined: Jul 07, 2011
Posts: 7
Hi All,

I have found this topic very useful. In our web application we are using Hibernate and the application is running well in local machines but when deployed in testing servers we are facing lazy initialization exception. i am providing my hbm file(due to security issues i am not including query part:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class lazy="false" name="org.myapp.domain.ClassProgram" table="CLS_PGM" mutable="true">
<meta attribute="extends">org.myapp.generic.domain.AuditedDomainObject</meta>
<id unsaved-value="null" name="code" type="java.lang.String" column="CLS_PGM_CDE">
<generator class="assigned" />
</id>
<property name="description" column="CLS_PGM_DSC" type="java.lang.String" />
<property name="name" column="CLS_PGM_NAM" type="java.lang.String" />
<property name="physicalClassProgram" column="PHYSCL_CLS_PGM" type="java.lang.String" />
<set name="tests" lazy="true" inverse="true" cascade="none">
<key>
<column name="CLS_PGM_CDE" />
</key>
<one-to-many class="org.myapp.domain.Class" />
</set>
</class>
<query name=""><![CDATA[

]]></query>
</hibernate-mapping>

In the above code i have changed <set name="tests" lazy="false" inverse="true" cascade="none">
the application is running fine but we are getting the 'lazy initialization exception' on the other assoiated class, in this case, its Class.

please let me know how to proceed to handle this exception.

Thanks,
Shehroze


Prakash Mani - Attur
Ranch Hand

Joined: Oct 08, 2009
Posts: 100
Guys,

Why the persistent classes should not be final if we use lazy. Basically how Hibernate get lazy object when we access it ?

Thanks.
shehroze sha
Greenhorn

Joined: Jul 07, 2011
Posts: 7
Could someone please answer my original question.

Thanks in Advance,
Shehroze
naresh voota
Greenhorn

Joined: Jun 04, 2007
Posts: 9
Shehroze,

Lazy initialization exception occurs because the hibernate session is closed. If you are getting an exception on Class, you must have a collection specified in the hbm with lazy="true"

Regards,
Naresh Voota.
shehroze sha
Greenhorn

Joined: Jul 07, 2011
Posts: 7
naresh voota wrote:Shehroze,

Lazy initialization exception occurs because the hibernate session is closed. If you are getting an exception on Class, you must have a collection specified in the hbm with lazy="true"

Regards,
Naresh Voota.



Naresh,

Thanks for the info.

But wanted to know how it affects the overall performance of the application if we change the lazy="false". Because as i said in my earlier thread after changing lazy="false" the application is running but still we are getting LazyInitializationException on the other associated class.. we have changed the value in the associated classes/collections but still we are getting LIE...

Thanks,
Shehroze
naresh voota
Greenhorn

Joined: Jun 04, 2007
Posts: 9
Shehroze,

Lazy intialization exception happens because hibernate does not support initialization of detached objects. I do not see any other reason. Are you sure the hibernate session which created the parent object is not closed? Even if you have a new session open, unless you merge the objects created in older sessions they will still give you Lazy initialization exception.

lazy="false" is not recommended unless there is an explicit reason to use it. lazy will fetch all the objects in the collection and you might not even use them. Getting the objects when you need them is better than loading on initialization. You might find the below documentation helpful.

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html

Regards,
Naresh Voota.
shehroze sha
Greenhorn

Joined: Jul 07, 2011
Posts: 7
Naresh,

Thank you very much for providing the useful info.

Now we are getting LazyInitializationException when we change the parameters in the log4j.xml:

For the below mentioned properties the applications runs well without any exception:
log4j.rootLogger=info, stdout

But, when we change the parameters as below we are getting lazyinitialization exception:
log4j.rootLogger=debug, stdout

Thanks,
Shehroze
 
jQuery in Action, 2nd edition
 
subject: what is lazy initialization in hibernate
 
Similar Threads
lazy initialization
General
org.hibernate.LazyInitializationException
Lazy Initialization
lazy loading