[英]Where should I open and close Hibernate session in Struts2 web app when using Hibernate Interceptors
我在Struts2應用程序中為每個CRUD操作使用了Hibernate Interceptor會話對象,因為我使用Hibernate Interceptor實現的對象打開了會話。
我只想在整個Struts2應用程序中每個請求僅使用一個Hibernate會話。
為此,我打開Struts中攔截休眠會話intercept()
方法和我關閉休眠會話中之前完成的Struts攔截intercept()
但是在我的應用程序中,我使用了“連鎖動作”調用。 那時,如果我嘗試在下一個鏈操作中使用Hibernate會話,則會收到Session close Exception
。
請幫助我在Struts2應用程序中打開和關閉Hibernate 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();
}
}
休眠攔截器實現類
public class MyHibernateInterceptor extends EmptyInterceptor{
//Override methods
}
當我使用鏈式動作時,調用invocation.invoke();
和session.close();
聲明被稱為2次。
您可以將會話設置為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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.