swamy
swamy

Reputation: 57

Where should I open and close Hibernate session in Struts2 web app when using Hibernate Interceptors

I am using Hibernate Interceptor's session object for each and every CRUD operation's in my Struts 2 application, for that I opened a session with Hibernate Interceptor's implemented object.

I want to use only one Hibernate session per one request in my entire Struts 2 application.

For this I opened a Hibernate session in Struts Interceptor intercept() method and I closed Hibernate session in Struts Interceptor intercept() before it is finished.

But, in my application I used 'chain action' calls. At that time, I am getting Session close Exception, if I try to use Hibernate session in the next chained action.

Please, help me where I open and close Hibernate Interceptor's session in Struts 2 application?

Interceptor:

public class MyStrutsInterceptor implements Interceptor {
  public void init() {
    // I created sessionfactroy object as a static variable 
  }

  public void destroy() {
    // I released the DB resources 
  }
  public String intercept(ActionInvocation invocation) throws Exception {
    Session session = sessionFactory().openSession(new MyHibernateInterceptor());
    invocation.invoke();
    session.close();
  }
}

Hibernate Interceptors implemented class

public class MyHibernateInterceptor extends EmptyInterceptor{  
    //Override methods
}

When I use a chained action call invocation.invoke(); and session.close();, the statement is called 2 times.

Upvotes: 1

Views: 779

Answers (1)

Roman C
Roman C

Reputation: 1

You can set a session to ThreadLocal

private static final ThreadLocal<Session> threadLocal = new ThreadLocal<>();

private static Session getSession() throws HibernateException {
  Session session = threadLocal.get();

  if (session == null || !session.isOpen()) {
    session = sessionFactory.openSession();
    threadLocal.set(session);
  }

  return session;
}

private static void closeSession() throws HibernateException {
  Session session = (Session) threadLocal.get();
  threadLocal.set(null);

  if (session != null) {
    session.close();
  }
}

public String intercept(ActionInvocation invocation) throws Exception {
  Session session = getSession();
  String result;
  try {
    result = invocation.invoke();
  } finally {
    closeSession();
  }
  return result;
}

Upvotes: 0

Related Questions