Wednesday, January 30, 2008

Hibrenate - Lazy Initialization (could not initialize proxy - the owning session was closed)

Hibernate object relational mapping offers both lazy and non-lazy modes of object initialization. Non-lazy initialization retrieves an object and all of its related objects at load time. This can result in hundreds if not thousands of select statements when retrieving one entity. The problem is compounded when bi-directional relationships are used, often causing entire databases to be loaded during the initial request. Of course one could tediously examine each object relationship and manually remove those most costly, but in the end, we may be losing the ease of use benefit sought in using the ORM tool.


Hibernate proxies can be very handy if you have performance concerns, the idea is to load the objects lazily as proxies and never hit the database. The proxies are initialized meaning fetched from the database when they are first accessed, however life is not so easy:) Whether there is a configured filter-interceptor of spring to manage hibernate sessions or you manually take care of the session’s life cycle, once the session was closed, the proxies attached to that will lead to a proxy initialization error if they are accessed later.

The reason is tricky, a hibernate session is created and some data is loaded to the session as a proxy, later the session is closed without an access to the proxy occurred. Then proxy is decided to be used and accessed, at this point one may get the error “no session or session was closed” since the session which the proxy is attached is “closed”. In order to deal with this situation there are some solutions.

1) Reloading the proxy “before” using it in the new session, this will attach the new proxy to the new session.

2) Using static method Hibernate.initialize(obj) before the owning session was closed, this will hit the db and replace the proxy with the actual data.

3) Using a Session lock via Session.lock(obj,lockmode), this will reattach the proxy to the new session.

4) Or you just disable lazy initialization mode by mark the flag into false (lazy=false)

As you see this proxy business isn’t simple as it seems but I belive once you learn how to use them they are the best way to optimize the performance.In the end who has not the need for speed?

No comments: