View RSS Feed

My Java Tips

Lazy select fetching for collections

Rate this Entry
by , 05-21-2011 at 10:30 PM (2066 Views)
Hibernate uses lazy select fetching for collections by default. This behavior makes sense and is used as it is unless you really want to do something different for some reason.

Hibernate will use the batch fetch optimization for lazy fetching if you set hibernate.default_batch_fetch_size. There is a problem with lazy fetching that should be considered. Remember, you should never access to a lazy association outside of the context of an open Hibernate session otherwise exceptions will greet you. The cause is simple, hibernate only loads the associations if needed and since the session is closed, it cannot load the asked association. Permissions collection in the given example is not initialized when the Session was closed.
For example:

Java Code:
s = sessions.openSession();
Transaction tx = s.beginTransaction();
            
User u = (User) s.createQuery("from Students u where u.name=:userName")
    .setString("userName", userName).uniqueResult();
Map permissions = u.getPermissions();

tx.commit();
s.close();

Integer rollNo = (Integer) permissions.get("rollNo");  // Error!
Solution: Get the rollNo from permissions before calling the close on hibernate session.

Submit "Lazy select fetching for collections" to Facebook Submit "Lazy select fetching for collections" to Digg Submit "Lazy select fetching for collections" to del.icio.us Submit "Lazy select fetching for collections" to StumbleUpon Submit "Lazy select fetching for collections" to Google

Tags: None Add / Edit Tags
Categories
Hibernate

Comments