public class HibernateUtil { private static Log log = LogFactory.getLog(HibernateUtil.class); private static final SessionFactory sessionFactory; //定義SessionFactory static { try { // 經過默認配置文件hibernate.cfg.xml建立SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { log.error("初始化SessionFactory失敗!", ex); throw new ExceptionInInitializerError(ex); } } //建立線程局部變量session,用來保存Hibernate的Session public static final ThreadLocal session = new ThreadLocal(); /** * 獲取當前線程中的Session * @return Session * @throws HibernateException */ public static Session currentSession() throws HibernateException { Session s = (Session) session.get(); // 若是Session尚未打開,則新開一個Session if (s == null) { s = sessionFactory.openSession(); session.set(s); //將新開的Session保存到線程局部變量中 } return s; } public static void closeSession() throws HibernateException { //獲取線程局部變量,並強制轉換爲Session類型 Session s = (Session) session.get(); session.set(null); if (s != null) s.close(); } }
/** * Created by IntelliJ IDEA. * User: leizhimin * Date: 2007-11-23 * Time: 10:45:02 * 學生 */ public class Student { private int age = 0; //年齡 public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } } /** * Created by IntelliJ IDEA. * User: leizhimin * Date: 2007-11-23 * Time: 10:53:33 * 多線程下測試程序 */ public class ThreadLocalDemo implements Runnable { //建立線程局部變量studentLocal,在後面你會發現用來保存Student對象 private final static ThreadLocal studentLocal = new ThreadLocal(); public static void main(String[] agrs) { ThreadLocalDemo td = new ThreadLocalDemo(); Thread t1 = new Thread(td, "a"); Thread t2 = new Thread(td, "b"); t1.start(); t2.start(); } public void run() { accessStudent(); } /** * 示例業務方法,用來測試 */ public void accessStudent() { //獲取當前線程的名字 String currentThreadName = Thread.currentThread().getName(); System.out.println(currentThreadName + " is running!"); //產生一個隨機數並打印 Random random = new Random(); int age = random.nextInt(100); System.out.println("thread " + currentThreadName + " set age to:" + age); //獲取一個Student對象,並將隨機數年齡插入到對象屬性中 Student student = getStudent(); student.setAge(age); System.out.println("thread " + currentThreadName + " first read age is:" + student.getAge()); try { Thread.sleep(500); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("thread " + currentThreadName + " second read age is:" + student.getAge()); } protected Student getStudent() { //獲取本地線程變量並強制轉換爲Student類型 Student student = (Student) studentLocal.get(); //線程首次執行此方法的時候,studentLocal.get()確定爲null if (student == null) { //建立一個Student對象,並保存到本地線程變量studentLocal中 student = new Student(); studentLocal.set(student); } return student; } }