HibernateUtil ThreadLocal

  1. HibernateUtil ThreadLocal
  2. import java.sql.SQLException;
  3. import org.hibernate.HibernateException;
  4. import org.hibernate.Session;
  5. import org.hibernate.SessionFactory;
  6. import org.hibernate.Transaction;
  7. import org.hibernate.cfg.Configuration;
  8. import java.sql.Connection;
  9. import org.apache.log4j.Logger;
  10. import java.io.File;
  11. public class HibernateUtil {
  12.     /**
  13.      * Loger4j的logger
  14.      */
  15.     private static final Logger logger = Logger.getLogger(HibernateUtil.class);
  16.     /**
  17.      * 存储hibernate session的ThreadLocal
  18.      */
  19.     private static final ThreadLocal sessionThread = new ThreadLocal();
  20.     /**
  21.      * 存储事务的ThreadLocal
  22.      */
  23.     private static final ThreadLocal transactionThread = new ThreadLocal();
  24.     /**
  25.      * Hibernate 的 Session工厂
  26.      */
  27.     private static SessionFactory sessionFactory = null;
  28.   /**
  29.      * 初始化SessionFactory
  30.      *
  31.      * @param file
  32.      *            Hibernate配置文件
  33.      */
  34.     public static void initSessionFactory(File file) {
  35.      Configuration config = new Configuration();
  36.      config.configure(file);
  37.      sessionFactory = config.buildSessionFactory();
  38.     }
  39.    /**
  40.      * 获取当前线程绑定的session
  41.      *
  42. * @return Session
  43.      * @throws HibernateException
  44.      */
  45.     public static Session getSession() {
  46.      Session s = (Session) sessionThread.get();
  47.      if (s == null) {
  48.       s = sessionFactory.openSession();
  49.       sessionThread.set(s);
  50.      } else {
  51.       Connection conn = s.connection();
  52.       try {
  53.        if (conn == null || conn.isClosed()) {
  54.         try {
  55.          s.close();
  56.         } catch (HibernateException e) {
  57.          logger.warn("close session error:" + e.getMessage(), e);
  58.         }
  59.         s = sessionFactory.openSession();
  60.         sessionThread.set(s);
  61.        }
  62.       } catch (SQLException e) {
  63.        throw new HibernateException(e);
  64.       }
  65.      }
  66.      return s;
  67.     }
  68.     /**
  69.      * 取得当前session的事务
  70.      *
  71.      * @return Transaction
  72.      */
  73.     public static Transaction transaction() {
  74.      Transaction transaction = (Transaction) transactionThread.get();
  75.      if (transaction == null) {
  76.       transaction = getSession().beginTransaction();
  77.       transactionThread.set(transaction);
  78.      }
  79.      return transaction;
  80.     }
  81.    /**
  82.      * 提交当前session的事务
  83.      */
  84.     public static void commitTransaction() {
  85.      Transaction transaction = (Transaction) transactionThread.get();
  86.      transactionThread.set(null);
  87.      if (transaction != null)
  88.       transaction.commit();
  89.     }
  90.    /**
  91.      * 回滚当前session的事务
  92.      */
  93.     public static void rollbackTransaction() {
  94.      Transaction tx = (Transaction) transactionThread.get();
  95.      transactionThread.set(null);
  96.      if (tx != null)
  97.       tx.rollback();
  98.     }
  99.    /**
  100.      * 关闭当前线程使用的session
  101.      */
  102.     public static void closeSession() {
  103.      Session session = (Session) sessionThread.get();
  104.      if (session != null) {
  105.       session.clear();
  106.       session.close();
  107.       sessionThread.set(null);
  108.      }
  109.     }
  110.    }
  111. CloseSessionFilter:
  112. import java.io.IOException;
  113. import javax.servlet.Filter;
  114. import javax.servlet.FilterChain;
  115. import javax.servlet.FilterConfig;
  116. import javax.servlet.ServletException;
  117. import javax.servlet.ServletRequest;
  118. import javax.servlet.ServletResponse;
  119. import javax.servlet.http.*;
  120. public class CloseSessionFilter implements Filter  {
  121.     protected FilterConfig config;
  122.     public void init(FilterConfig config) throws ServletException {
  123.         this.config=config;
  124.         
  125.     }
  126.     public void destroy() {
  127.         config=null;
  128.     }
  129.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain 
  130. chain) throws IOException, ServletException {
  131.         try{
  132.         chain.doFilter((HttpServletRequest)request,(HttpServletResponse)response);
  133.         }
  134.         finally
  135.         {
  136.             try{
  137.                 HibernateUtil.commitTransaction();
  138.             }
  139.             catch(Exception e){
  140.                 HibernateUtil.rollbackTransaction();
  141.             }
  142.             finally
  143.             {
  144.                 HibernateUtil.closeSession();
  145.             }
  146.         }
  147.     }
  148.     
  149. }
  150. Test.java:
  151.  HibernateUtil.initSessionFactory(new File(Test.class.getClassLoader().getResource
  152. ("hibernate.cfg.xml").getFile()));
  153.           Session se = HibernateUtil.getSession();
  154. Query query = se.getNamedQuery("CatgQuery");
  155.         List list= query.list();
  156. Iterator iter= list.iterator();
  157.         while(iter.hasNext()){
  158.             Catg temp=(Catg)iter.next();
  159.             System.out.println(temp.getId() + ":" + temp.getCname()
  160. +","+temp.getCount());
  161.         }   
  162. HibernateUtil.closeSession();
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值