Lazy Fetching in Hibernate with Example

Lazy fetching is associated with child objects loading for its parents. While loading the parent, the selection of loading a child object is to be specified / mentioned in the hbm.xml file. Hibernate does not load the whole child objects by default. Lazy=true means not to load the child objects.

Lazy Instances and Proxies:

Transaction tx = session.beginTransaction();
Query query = session.createQuery(
 "from Book b where b.bookName=:name");
query.setParameter("name", "Hibernate");
List list = (List)query.list( );
tx.commit();
for(Book b : list ) {
System.out.println("Location"+ b.getLocation().getName());
}

Error:  LazyInstantiationException
  • Hibernate uses lazy instantiation and proxy objects
  • Hibernate instantiates the book object when it is first accessed
  • We closed the transaction before accessing the location 
Solution 1: Modify Book.hbm.xml file not to use lazy instantiation of Book objects.

<class name="Book" table="Book" lazy="false">
...
...
...
</class>

Solution2: Modift the source code like below.


for(Book b : list ) {
System.out.println("Location"+ b.getLocation().getName());
}
tx.commit();
Call the getLocation( ) method before closing the session.

Search:

Recent Posts