We all face the common problem with Hibernate of LazyInitializationException.
This happens to any decent application which has hibernate related code separated out in DAO layer and lazy loading is been turned on.
What happens is
- You retrieve some object from database using hibernate session and pass it back to helper / service layer for further processing.
- Service layer start processing the bean that was passed to it. it tries to read some property etc. and then we hit the dreaded LazyInitializationException: Session is closed.
- What happened was, DAO got the object from the session and before passing on the object to service layer, the session was closed!
- Since the session is closed without initializing the proxies, when you try to access the object properties (or contained sub-objects) you would face the exception.
There is no "Real" solution to this issue. we can only come up with few strategies. one of the strategies that I liked is "Open Session in View" pattern.
"Open Session in View" basically means, you open the database session when you start servicing for your view; and keep the session open till you have fully rendered your view and then only close the hibernate session.
Simple way to implement this is to write a web-app filter which would intercept your request, open a db session. let you work on your request. anywhere (DAO / Service / Action) you work on the objects retrieved from database, proxies would still hold good. Once your view (jsp) is completely rendered, filter on its way of finishing the activity closes the session.
Another nice side effect of this pattern is now your DAO does not need to have boilerplate code to open / close the session. Just get the current session from a singleton instance of HibernateUtil.
More details on this pattern implementation for hibernate:
Open Session in View
Looks really promising.
If you are using Spring, spring already has such filter written for you. :
Open Session In View FilterCaveats:
- Above pattern would not hold good in 3 tier application (e.g. where EJBs decouple the web and service layer). thats because the session that you got initialized in web layer wont be available inside EJB Container.
- Few people DO think that this pattern binds Presentation layer with Hibernate (Data Access implementation). As of now, I do not think that's the case. My thought process was driven by following discussion threads.
i.
hibernate forum threadii.
Raible design thread
Would be looking for making implementation of this one in my next project.
That's all till the next time.
--VJ