我正在使用Struts 2.2.1.1和Hibernate 3.6.2.Final。我也使用C3P0作为我在Tomcat 7.0.11上运行的连接池。
我遇到的问题是我的Hibernate Sessions没有被关闭,而且我很快超过了“hibernate.c3p0.max_size”属性中配置的最大打开连接数。
我认为这是因为我的Hibernate会话已经打开但从未关闭过。我正在从存储在ServletContext中的SessionFactory中打开Sessions。我尝试在我的Action类的finally {}块中关闭会话,但是抛出了org.hibernate.LazyInitializationException异常。
我做了一些研究,我发现了Full Hibernate Plugin方法以及Open Session in View方法。
我认为这是一个常见问题,我想了解最常用的解决方案。
我注意到的另一件事是Full Hibernate Plugin支持Struts 2.0.9+到2.1.6,但我使用的是2.2.1.1。不确定这是不是问题,或者网站是否尚未更新以列出新版本。
非常感谢任何输入。
答案 0 :(得分:1)
我从未使用过hibernate插件,但我鼓励您采用 Open View in View 模式。你肯定想结束你的会议。
处理此问题的最常见方法之一是在请求开始时创建会话,将其存储在本地线程中,然后在请求结束时将其关闭。这可以通过Struts拦截器或servlet过滤器完成。基本上是:
public class HibernateSessionInterceptor extends AbstractInterceptor {
@Override
public String intercept(final ActionInvocation invocation) throws Exception {
try {
// create the session and place it in the ThreadLocal
return invocation.invoke();
} finally {
// close the session and remove it from the ThreadLocal
}
}
}
如果您使用Google Guice,则会有一个基于JPA的持久性插件(guice-persist)。它使用相同的方法,但使用servlet过滤器。