could not initialize proxy – the owning session was closed
November 3, 2005 4 Comments
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.
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?