I am now the owner of a Struts-1 application, and the Hibernate session management is all over the place. I have searched online documentation but have not found a clear explanation of the best way to manage Hibernate sessions in a Struts application. Presumably a Hibernate Session should be created (or fetched) at the start of each action, and a transaction opened, and then the transaction committed or rolled back at the end of the action. Is that correct? How can this be managed for all actions without duplicating code in each action? Should each Action fetch objects from the DB, call model functions, and then save the objects, ala Ruby on Rails?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
I don't think struts 1 ships with an OpenSessionInView filter, but one way to manage sessions is opening sessions on a per-request basis, which are then accessed via the thread local pattern.
This will keep the session open until the request is done rendering, meaning you can use lazily instantiated collections in your views safely.
Spring ships with an opensessioninview filter, here is an article on how to use it, or, it's relatively straightforward to write your own as a standard servlet filter.
to write your own, you would write ServletFilter that implements Filter, and implement a doFilter method. it would look something like:
you would need to register this filter in your web.xml, and apply it to the URLs that you need sessions with. This is not the most elegant solution in the world, but it does work just fine.