Hiberate with Struts2 - Use Full Hibernate Plugin or another method to close Sessions?

╄→尐↘猪︶ㄣ 提交于 2019-12-18 09:37:23

问题


I'm using Struts 2.2.1.1 and Hibernate 3.6.2.Final. I'm also using C3P0 for my connection pool which is running on Tomcat 7.0.11.

I'm having issues where my Hibernate Sessions are not being closed and I'm quickly exceeding the maximum number of open connections as configured in the "hibernate.c3p0.max_size" property.

I think it is because my Hibernate Sessions are opened but never closed. I'm opening Sessions from a SessionFactory that is stored in the ServletContext. I tried closing the session in a finally{} block on my Action class but that throws org.hibernate.LazyInitializationException exceptions.

I did some research and I found the Full Hibernate Plugin approach and also the Open Session in View approach.

I'm assuming this is a common problem and I'd like to get a feel for the most commonly used solution.

Another thing I noticed is the Full Hibernate Plugin supports Struts 2.0.9+ to 2.1.6 but I'm using 2.2.1.1. Not sure if this would be a problem or if the website just hasn't been updated to list the newer version.

Any input is much appreciated.


回答1:


I've never used the hibernate plugin, but I would encourage you to adopt the Open Session in View pattern. You definitely want to be closing your sessions.

One of the most common ways to handle this is to create a session at the start of the request, store it in a thread local, and then close it at the end of the request. This can be done from a Struts interceptor or a servlet filter. Basically:

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
        }
    }
}

If you use Google Guice, there is a persistence plugin (guice-persist) that is based on JPA. It uses the same approach, but with a servlet filter.



来源:https://stackoverflow.com/questions/5901137/hiberate-with-struts2-use-full-hibernate-plugin-or-another-method-to-close-ses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!