Hibernate – Lazy loading issues
Nov 14, 2007 by Will Mernagh
So I am implementing the DB access via Hibernate. Hibernate makes it easy to persist objects that map to multiple tables. In my case I have a Rounds object that contains Games objects that contains Teams objects. Hibernate allows me to persist a Rounds object and it will automatically persist all the Games objects and create the mapping in the rounds_games table (see here for my ERD)
One of the cool features of Hibernate is when loading a Rounds object from a DB it, by default, does a Lazy load. This lazy loads Rounds but not the members that are persisted in different tables (i.e. Games in my case). Instead it loads a proxy instead. Thus upon calling a Rounds getGames() method Hibernate will then load (via the proxy) the Games. This only works however if you have a hibernate session open. (See ** below for why this may not always be possible)
This approach is the default because it is much more efficient than loading all table info.
For example if you were looking for only a number of Rounds objects in a DB and loaded them all to iterate through them and perform some operation on ones that meet a certain requirement. It would be extremely inefficient to load all Rounds objects and all their Games objects and all the Games object’s Teams objects.
However for my application I load individual Rounds objects only and I always need the Games objects and Teams objects loaded. I also hide my Hibernate implementation behind a RoundManager DataAccessObject. So when I retrieve the Object from the manager the connection to the DB is closed and the access to the Games members will throw a LazyInitilizationException.
So I changed the default from lazy=true to lazy=false and it loads all members before returning the Rounds object
In my Rounds.hbm.xml I now have the following
Note also that I had to update the Games.hbm.xml file also so that it did not Lazy load Teams
** This is not always possible because the view may be accessing the Rounds object’s Games. If the sessions is closed before the view is rendered then there will be a LazyInitilizationException thrown. In many 3-tier applications the view will never be able to have access to the hibernate session. See this article for some thoughts and ideas about this general issue
blog comments powered by Disqus