Lazy associations – I
30 August 2008Hibernate uses lazy select fetching by default for collections and lazy proxy fetching for single-valued associations. This default behavior makes sense for almost all associations in almost all applications.
Hibernate will use the batch fetch optimization for lazy fetching if hibernate.default_batch_fetch_size parameter is set. This optimization may also be enabled at a more granular level.
Lazy fetching introduces a problem that should be taken care of. Remember that access to a lazy association outside of the context of an open Hibernate session will result in an exception. Review the code snippet bellow:
s = sessions.openSession(); Transaction tx = s.beginTransaction(); User u = (User) s.createQuery("from User u where u.name=:userName") .setString("userName", userName).uniqueResult(); Map permissions = u.getPermissions(); tx.commit(); s.close(); Integer accessLevel = (Integer) permissions.get("accounts"); // Error!
The last line of code will report an exception because the permissions collection was not initialized when the Session was closed. Therefore, the collection will not be able to load its state.
continued …
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Lazy associations – I