Lazy select fetching for collections
by, 05-21-2011 at 10:30 PM (2483 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.
Solution: Get the rollNo from permissions before calling the close on hibernate session.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!