利用过滤器对hibernate的session管理,实现session在线程范围内的共享

  hibernate中的 Session关系到对数据库的增删查改等基本的数据存取操作.对 Session进行有效的维护,就像是在jdbc编程中对JDBC collection的维护.
     在struts+ hibernate的方案中,常常利用过滤器(Filter)对 session进行管理,以实现 session在线程范围内的共享.为什么仅仅实现线程内的共享,是因为,不能把 session用于多线程,否则会出现意外.在线程范围内实现sesion的共享.避免了 session的频繁的创建和销毁.我看到有的程序中,在单个方法内,打开 session,执行.关闭 session.这显然没有在一次会话中有效的利用 session
     下面的方案是.通过建立一个过滤器,以实现对sesion的共享:
Java代码
  1. package com.cs_oj.filter;   
  2.   
  3. import java.io.IOException;   
  4. import java.text.DateFormat;   
  5. import java.text.SimpleDateFormat;   
  6. import java.util.Date;   
  7.   
  8. import javax.servlet.Filter;   
  9. import javax.servlet.FilterChain;   
  10. import javax.servlet.FilterConfig;   
  11. import javax.servlet.ServletException;   
  12. import javax.servlet.ServletRequest;   
  13. import javax.servlet.ServletResponse;   
  14. import javax.servlet.http.HttpServletRequest;   
  15. import javax.servlet.http.HttpServletResponse;   
  16. import javax.servlet.http.Http<SPAN class=hilite2>Session</SPAN>;   
  17.   
  18. import org.apache.commons.logging.Log;   
  19. import org.apache.commons.logging.LogFactory;   
  20. import org.<SPAN class=hilite1>hibernate</SPAN>.<SPAN class=hilite2>Session</SPAN>;   
  21. import org.<SPAN class=hilite1>hibernate</SPAN>.Transaction;   
  22.   
  23.   
  24. import com.cs_oj.data.dao.<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory;   
  25.   
  26. public class <SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter implements Filter {   
  27.     private static final Log log = LogFactory.getLog(<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter.class);   
  28.     public void destroy() {   
  29.         // TODO Auto-generated method stub   
  30.   
  31.     }   
  32.   
  33.     public void doFilter(ServletRequest arg0, ServletResponse arg1,   
  34.             FilterChain chain) throws IOException, ServletException {   
  35.         log.debug("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter start");   
  36.         Date date=new Date();   
  37.         DateFormat df=new SimpleDateFormat("yyyy-MM-dd '时间--'HH:mm:ss");   
  38.         System.out.println("----当前时间:"+df.format(date)+"----");   
  39.         System.out.println("----------<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter start-----------");   
  40.   
  41. //利用<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory, 得到当 前线程中的<SPAN class=hilite2>session</SPAN>对象..<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory的代码利用了ThreadLocal模式..详见..<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory   
  42.         <SPAN class=hilite2>Session</SPAN> <SPAN class=hilite2>session</SPAN>=<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory.get<SPAN class=hilite2>Session</SPAN>();    
  43.         log.info("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin transaction");   
  44.         System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin transaction");   
  45.        Transaction tx=<SPAN class=hilite2>session</SPAN>.beginTransaction();   //开始事务   
  46.            
  47.         log.debug("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin doChain");   
  48.         HttpServletResponse response=(HttpServletResponse)arg1;   
  49.         try{   
  50.             chain.doFilter(arg0, arg1);   
  51.                
  52.             log.debug("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin commit");   
  53.             //没有异常,则提交   
  54.             try{   
  55.                    
  56.                 System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin commit");   
  57.                 tx.commit();   
  58.                 System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter commit success");   
  59.                    
  60.             }   
  61.             catch(Exception e){   
  62.                    
  63.                 System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter commit failed");   
  64.                 System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin rollback() ");   
  65.                 try{   
  66.                     System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin rollback() ");   
  67.                     tx.rollback();   
  68.                     System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter rollback() success ");   
  69.                 }catch(RuntimeException ex){   
  70.                     System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter   rollback() failed");   
  71.                 }   
  72.             }   
  73.         }catch (Exception e) {   
  74.             e.printStackTrace();   
  75.             System.out.println("chain.doFilter(arg0, arg1) exception accurs ");   
  76.             System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin rollback() ");   
  77.             tx.rollback();   //出现异常,回滚   
  78.             //response.sendRedirect("error.jsp");   
  79.         }   
  80.         finally{   
  81.             log.debug("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter end doChain");   
  82.             System.out.println("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin close <SPAN class=hilite2>session</SPAN>");   
  83.            <SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory.close<SPAN class=hilite2>Session</SPAN>();   
  84.             System.out.println("*********<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter close <SPAN class=hilite2>session</SPAN> success*********");   
  85.             log.debug("<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter begin close <SPAN class=hilite2>session</SPAN>");   
  86.             //System.out.println("<SPAN class=hilite2>session</SPAN>.isOpen()="+<SPAN class=hilite2>session</SPAN>.isOpen());   
  87.         }   
  88.   
  89.     }   
  90.   
  91. }  
package com.cs_oj.filter;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;


import com.cs_oj.data.dao.HibernateSessionFactory;

public class HibernateSessionFilter implements Filter {
    private static final Log log = LogFactory.getLog(HibernateSessionFilter.class);
    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain chain) throws IOException, ServletException {
        log.debug("HibernateSessionFilter start");
        Date date=new Date();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd '时间--'HH:mm:ss");
        System.out.println("----当前时间:"+df.format(date)+"----");
        System.out.println("----------HibernateSessionFilter start-----------");

//利用HibernateSessionFactory, 得到当 前线程中的session对象..HibernateSessionFactory的代码利用了ThreadLocal模式..详见..HibernateSessionFactory
        Session session=HibernateSessionFactory.getSession(); 
        log.info("HibernateSessionFilter begin transaction");
        System.out.println("HibernateSessionFilter begin transaction");
       Transaction tx=session.beginTransaction();   //开始事务
        
        log.debug("HibernateSessionFilter begin doChain");
        HttpServletResponse response=(HttpServletResponse)arg1;
        try{
            chain.doFilter(arg0, arg1);
            
            log.debug("HibernateSessionFilter begin commit");
            //没有异常,则提交
            try{
                
                System.out.println("HibernateSessionFilter begin commit");
                tx.commit();
                System.out.println("HibernateSessionFilter commit success");
                
            }
            catch(Exception e){
                
                System.out.println("HibernateSessionFilter commit failed");
                System.out.println("HibernateSessionFilter begin rollback() ");
                try{
                    System.out.println("HibernateSessionFilter begin rollback() ");
                    tx.rollback();
                    System.out.println("HibernateSessionFilter rollback() success ");
                }catch(RuntimeException ex){
                    System.out.println("HibernateSessionFilter   rollback() failed");
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("chain.doFilter(arg0, arg1) exception accurs ");
            System.out.println("HibernateSessionFilter begin rollback() ");
            tx.rollback();   //出现异常,回滚
            //response.sendRedirect("error.jsp");
        }
        finally{
            log.debug("HibernateSessionFilter end doChain");
            System.out.println("HibernateSessionFilter begin close session");
           HibernateSessionFactory.closeSession();
            System.out.println("*********HibernateSessionFilter close session success*********");
            log.debug("HibernateSessionFilter begin close session");
            //System.out.println("session.isOpen()="+session.isOpen());
        }

    }

}

 

 

 

在web.xml文件中对上面的过滤器进行配置.

Xml代码 复制代码
  1. <filter>  
  2.     <filter-name><SPAN class=hilite1>hibernate</SPAN><SPAN class=hilite2>Session</SPAN></filter-name>  
  3.     <filter-class>com.cs_oj.filter.<SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Filter</filter-class>  
  4. </filter>  
  5. <filter-mapping>  
  6.     <filter-name><SPAN class=hilite1>hibernate</SPAN><SPAN class=hilite2>Session</SPAN></filter-name>  
  7.     <servlet-name>action</servlet-name>  
  8.       
  9. </filter-mapping>  
  10. <servlet>  
  11.     <servlet-name>action</servlet-name>  
  12.     <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>  
  13.     <init-param>.   
  14.     <init-param>  
  15.       <param-name>config</param-name>  
  16.       <param-value>/WEB-INF/struts-config.xml</param-value>  
  17.     </init-param>  
  18.     <init-param>  
  19.       <param-name>debug</param-name>  
  20.       <param-value>3</param-value>  
  21.     </init-param>  
  22.     <init-param>  
  23.       <param-name>detail</param-name>  
  24.       <param-value>3</param-value>  
  25.     </init-param>  
  26.     <load-on-startup>0</load-on-startup>  
  27. </servlet>  
  28. <servlet-mapping>  
  29.     <servlet-name>action</servlet-name>  
  30.     <url-pattern>*.do</url-pattern>  
  31. </servlet-mapping>  

 

 

则对所有以.do作为后缀名的url,都会被过滤器过滤.在被过滤器过滤的action中,和业务层的方法内,只需要调用HibernateSessionFactory 的getSession()方法,得到当前线程内的session对象.用完session后,不要关闭session,而且,每次在用session进行添加和修改操作时,也不需要启动事务.

 

HibernateSessionFactory.java

Java代码
  1. package com.cs_oj.data.dao;   
  2.   
  3. import org.<SPAN class=hilite1>hibernate</SPAN>.<SPAN class=hilite1>Hibernate</SPAN>Exception;   
  4. import org.<SPAN class=hilite1>hibernate</SPAN>.<SPAN class=hilite2>Session</SPAN>;   
  5. import org.<SPAN class=hilite1>hibernate</SPAN>.cfg.Configuration;   
  6.   
  7.   
  8. public class <SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory {   
  9.   
  10.     /**   
  11.      * Location of <SPAN class=hilite1>hibernate</SPAN>.cfg.xml file.  
  12.      * Location should be on the classpath as <SPAN class=hilite1>Hibernate</SPAN> uses   
  13.      * #resourceAsStream style lookup for its configuration file.   
  14.      * The default classpath location of the <SPAN class=hilite1>hibernate</SPAN> config file is   
  15.      * in the default package. Use #setConfigFile() to update   
  16.      * the location of the configuration file for the current <SPAN class=hilite2>session</SPAN>.     
  17.      */  
  18.     private static String CONFIG_FILE_LOCATION = "/<SPAN class=hilite1>hibernate</SPAN>.cfg.xml";   
  19.     private static final ThreadLocal<<SPAN class=hilite2>Session</SPAN>> threadLocal = new ThreadLocal<<SPAN class=hilite2>Session</SPAN>>();   
  20.     private static Configuration configuration = new Configuration().configure();   
  21.     private static org.<SPAN class=hilite1>hibernate</SPAN>.<SPAN class=hilite2>Session</SPAN>Factory <SPAN class=hilite2>session</SPAN>Factory;   
  22.     private static String configFile = CONFIG_FILE_LOCATION;   
  23.   
  24.     private <SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory() {   
  25.     }   
  26.        
  27.     /**  
  28.      * Returns the ThreadLocal <SPAN class=hilite2>Session</SPAN> instance. Lazy initialize  
  29.      * the <code><SPAN class=hilite2>Session</SPAN>Factory</code> if needed.  
  30.      *  
  31.      * @return <SPAN class=hilite2>Session</SPAN>  
  32.      * @throws <SPAN class=hilite1>Hibernate</SPAN>Exception  
  33.      */  
  34.     public static <SPAN class=hilite2>Session</SPAN> get<SPAN class=hilite2>Session</SPAN>() throws <SPAN class=hilite1>Hibernate</SPAN>Exception {   
  35.         <SPAN class=hilite2>Session</SPAN> <SPAN class=hilite2>session</SPAN> = threadLocal.get();   
  36.   
  37.         if (<SPAN class=hilite2>session</SPAN> == null || !<SPAN class=hilite2>session</SPAN>.isOpen()) {   
  38.             if (<SPAN class=hilite2>session</SPAN>Factory == null) {   
  39.                 rebuild<SPAN class=hilite2>Session</SPAN>Factory();   
  40.             }   
  41.             <SPAN class=hilite2>session</SPAN> = (<SPAN class=hilite2>session</SPAN>Factory != null) ? <SPAN class=hilite2>session</SPAN>Factory.open<SPAN class=hilite2>Session</SPAN>()   
  42.                     : null;   
  43.             threadLocal.set(<SPAN class=hilite2>session</SPAN>);   
  44.         }   
  45.   
  46.         return <SPAN class=hilite2>session</SPAN>;   
  47.     }   
  48.   
  49.     /**  
  50.      * Rebuild <SPAN class=hilite1>hibernate</SPAN> <SPAN class=hilite2>session</SPAN> factory  
  51.      *  
  52.      */  
  53.     public static void rebuild<SPAN class=hilite2>Session</SPAN>Factory() {   
  54.         try {   
  55.             //configuration.configure();   
  56.             <SPAN class=hilite2>session</SPAN>Factory = configuration.build<SPAN class=hilite2>Session</SPAN>Factory();   
  57.         } catch (Exception e) {   
  58.             System.err   
  59.                     .println("%%%% Error Creating <SPAN class=hilite2>Session</SPAN>Factory %%%%");   
  60.             e.printStackTrace();   
  61.         }   
  62.     }   
  63.   
  64.     /**  
  65.      * Close the single <SPAN class=hilite1>hibernate</SPAN> <SPAN class=hilite2>session</SPAN> instance.  
  66.      *  
  67.      * @throws <SPAN class=hilite1>Hibernate</SPAN>Exception  
  68.      */  
  69.     public static void close<SPAN class=hilite2>Session</SPAN>() throws <SPAN class=hilite1>Hibernate</SPAN>Exception {   
  70.         <SPAN class=hilite2>Session</SPAN> <SPAN class=hilite2>session</SPAN> = threadLocal.get();   
  71.         threadLocal.set(null);   
  72.   
  73.         if (<SPAN class=hilite2>session</SPAN> != null) {   
  74.             <SPAN class=hilite2>session</SPAN>.close();   
  75.         }   
  76.     }   
  77.   
  78.     /**  
  79.      * return <SPAN class=hilite2>session</SPAN> factory  
  80.      *  
  81.      */  
  82.     public static org.<SPAN class=hilite1>hibernate</SPAN>.<SPAN class=hilite2>Session</SPAN>Factory get<SPAN class=hilite2>Session</SPAN>Factory() {   
  83.         return <SPAN class=hilite2>session</SPAN>Factory;   
  84.     }   
  85.   
  86.     /**  
  87.      * return <SPAN class=hilite2>session</SPAN> factory  
  88.      *  
  89.      *    <SPAN class=hilite2>session</SPAN> factory will be rebuilded in the next call  
  90.      */  
  91.     public static void setConfigFile(String configFile) {   
  92.         <SPAN class=hilite1>Hibernate</SPAN><SPAN class=hilite2>Session</SPAN>Factory.configFile = configFile;   
  93.         <SPAN class=hilite2>session</SPAN>Factory = null;   
  94.     }   
  95.   
  96.     /**  
  97.      * return <SPAN class=hilite1>hibernate</SPAN> configuration  
  98.      *  
  99.      */  
  100.     public static Configuration getConfiguration() {   
  101.         return configuration;   
  102.     }   
  103.   
  104. }  
  105. package com.cs_oj.data.dao;

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


    public class HibernateSessionFactory {

        /**
         * Location of hibernate.cfg.xml file.
         * Location should be on the classpath as Hibernate uses
         * #resourceAsStream style lookup for its configuration file.
         * The default classpath location of the hibernate config file is
         * in the default package. Use #setConfigFile() to update
         * the location of the configuration file for the current session.  
         */
        private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
        private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
        private static Configuration configuration = new Configuration().configure();
        private static org.hibernate.SessionFactory sessionFactory;
        private static String configFile = CONFIG_FILE_LOCATION;

        private HibernateSessionFactory() {
        }
       
        /**
         * Returns the ThreadLocal Session instance. Lazy initialize
         * the <code>SessionFactory</code> if needed.
         *
         * @return Session
         * @throws HibernateException
         */
        public static Session getSession() throws HibernateException {
            Session session = threadLocal.get();

            if (session == null || !session.isOpen()) {
                if (sessionFactory == null) {
                    rebuildSessionFactory();
                }
                session = (sessionFactory != null) ? sessionFactory.openSession()
                        : null;
                threadLocal.set(session);
            }

            return session;
        }

        /**
         * Rebuild hibernate session factory
         *
         */
        public static void rebuildSessionFactory() {
            try {
                //configuration.configure();
                sessionFactory = configuration.buildSessionFactory();
            } catch (Exception e) {
                System.err
                        .println("%%%% Error Creating SessionFactory %%%%");
                e.printStackTrace();
            }
        }

        /**
         * Close the single hibernate session instance.
         *
         * @throws HibernateException
         */
        public static void closeSession() throws HibernateException {
            Session session = threadLocal.get();
            threadLocal.set(null);

            if (session != null) {
                session.close();
            }
        }

        /**
         * return session factory
         *
         */
        public static org.hibernate.SessionFactory getSessionFactory() {
            return sessionFactory;
        }

        /**
         * return session factory
         *
         *    session factory will be rebuilded in the next call
         */
        public static void setConfigFile(String configFile) {
            HibernateSessionFactory.configFile = configFile;
            sessionFactory = null;
        }

        /**
         * return hibernate configuration
         *
         */
        public static Configuration getConfiguration() {
            return configuration;
        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值