---
title: "ThreadLocal在hiberate中的使用"
author: "dmwdmc"
date: "2013-06-05T10:16:05Z"
tags: []
categories: ["编程语言"]
slug: "threadlocal-hiberate"
draft: false
lastmod: "2013-06-04T21:50:53Z"
id: 1882355
url: "https://dmwdmc.iteye.com/blog/1882355"
---

public class HibernateUtil {  
   2.        public static final SessionFactory sessionFactory;  
   3.        static {  
   4.            try {  
   5.                  sessionFactory = new Configuration().configure()  
   6.                                    .buildSessionFactory();  
   7.            } catch (Throwable ex) {  
   8.                 throw new ExceptionInInitializerError(ex);  
   9.            }  
  10.        }  
  11.        public static final ThreadLocal session =   
  12.                                             new ThreadLocal();  
  13.        public static Session currentSession() throws HibernateException {  
  14.                Session s = session.get();  
  15.                if(s == null) {  
  16.                      s = sessionFactory.openSession();  
  17.                      session.set(s);  
  18.                }  
  19.                return s;  
  20.        }  
  21.        public static void closeSession() throws HibernateException {  
  22.                 Session s = session.get();  
  23.                 if(s != null) {  
  24.                       s.close();  
  25.                 }  
  26.                 session.set(null);  
  27.        }  
  28. }