0

I am trying to open Hibernate Session on each request and close it at the end.

This seems like it could work, but I have now idea how am I supposed to put my Session object in ThreadLocal and answer does not explain that.

Is there any Struts2 specific way to do this?

Community
  • 1
  • 1
Eleeist
  • 6,891
  • 10
  • 50
  • 77

1 Answers1

1

You can add a HttpFilter that is in front of the Struts2 Servlet. In the filter:

public class SessionProviderFilter implements Filter {
    private static ThreadLocal<Session> sessionStore = new ThreadLocal<Session>();


    public void doFilter(...) {
        Session session = ... // get the session
        sessionStore.set(session);
        chain.doFilter(...);
        sessionStore.set(null);
   }

   public static Session getCurrentSession() {
        return sessionStore.get();
   }
}

Now from any code, to get current hibernate session, you call SessionProviderFilter.getCurrentSession().

Καrτhικ
  • 3,833
  • 2
  • 29
  • 42