hibernate Session在OpenSessionInView资源的获得和关闭

这是一个过滤器,用于确保关闭session资源,也用于获得session资源:HibernateFilter.getSession()


import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateFilter implements Filter {
	
	private static ThreadLocal hibernaThreadLocal = new ThreadLocal();
	private static SessionFactory factory;

	public void destroy() {
		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		try {
			//加载页面之前
			filterChain.doFilter(servletRequest, servletResponse);
		}finally {
			//页面加载完hibernate使用的对象后关闭资源
			Session session = (Session)hibernaThreadLocal.get();
			if(session != null) {
				if(session.isOpen()) {
					session.close();
				}
				hibernaThreadLocal.remove();
			}
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		try {
			Configuration cfg = new Configuration().configure();
			factory = cfg.buildSessionFactory();
		}catch(Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
		
	}
	
	public static Session getSession() {
		Session session = (Session)hibernaThreadLocal.get();
		if(session == null) {
			session = factory.openSession();
			hibernaThreadLocal.set(session);
		}
		return session;
	}
}

你可能感兴趣的:(Hibernate,servlet)