【问题标题】:Hiberate with Struts2 - Use Full Hibernate Plugin or another method to close Sessions?Hibernate with Struts2 - 有用的 Hibernate 插件或其他关闭会话的方法?
【发布时间】:2011-08-19 13:23:27
【问题描述】:

我正在使用 Struts 2.2.1.1 和 Hibernate 3.6.2.Final。我还将 C3P0 用于在 Tomcat 7.0.11 上运行的连接池。

我遇到的问题是我的 Hibernate 会话没有关闭,并且我很快超过了“hibernate.c3p0.max_size”属性中配置的最大打开连接数。

我认为这是因为我的 Hibernate 会话已打开但从未关闭。我正在从存储在 ServletContext 中的 SessionFactory 打开 Sessions。我尝试在 Action 类的 finally{} 块中关闭会话,但这会引发 org.hibernate.LazyInitializationException 异常。

我做了一些研究,发现了Full Hibernate Plugin 方法和Open Session in View 方法。

我假设这是一个常见问题,我想了解一下最常用的解决方案。

我注意到的另一件事是 Full Hibernate 插件支持 Struts 2.0.9+ 到 2.1.6,但我使用的是 2.2.1.1。不确定这是否是个问题,或者网站是否只是没有更新以列出较新的版本。

非常感谢任何意见。

【问题讨论】:

    标签: hibernate struts2 struts2-s2hibernate


    【解决方案1】:

    我从未使用过 hibernate 插件,但我鼓励您采用 Open Session 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 过滤器。

    【讨论】:

    • 谢谢史蒂文·贝尼特斯。再次发现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多