Hibernate Sessions – Best Way to Manage Hibernate Sessions in a Struts-1 Application

hibernatejavajava-eestruts

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?

Best Answer

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:

void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) {
   Session session;
   try {
      session = // get my hibernate session here
      // do the request
      chain.doFilter(req, res);
   } catch (Whatever) {
   } finally {
     // close my session here
   }

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.