Hibernate中兩種獲取Session的方式

Session:是應用程序與數據庫之間的一個會話,Hibernate運作的中心,持久層操作的基礎.對象的生命週期/事務的管理/數據庫的存取都與Session息息相關.

  Session對象是通過SessionFactory構建的,下面舉個例子來介紹Hibernate兩種獲取session的方式。

  日誌,是編程中很常見的一個關注點.用戶在對數據庫進行操作的過程需要將這一系列操作記錄,以便跟蹤數據庫的動態.那麼一個用戶在向數據庫插入一條記錄的時候,就要向日志文件中記錄一條記錄,用戶的一系列操作都要在一個Session中進行,否則這就成爲了兩個線程.不能保證同步.看下面的代碼

     HibernateUtil管理Session的工具類

  

  1. package com.bjpowernode.usermgr.util;  
  2.   
  3. import org.hibernate.Session;//hibernate3的  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6.   
  7. public class HibernateUtils {  
  8.    private static SessionFactory factory;  
  9.       
  10.    static{  
  11.            try{  
  12.             //讀取hibernate.cfg.xml文件  
  13.             Configuration cfg=new Configuration().configure();  
  14.                
  15.             //建立SessionFactory  
  16.             factory=cfg.buildSessionFactory();  
  17.      
  18.            }catch(Exception e){  
  19.               e.printStackTrace();   
  20.            }  
  21.    }    
  22.      
  23.       //獲得開啓着的Session  
  24.    public static Session getSession(){  
  25.        return factory.openSession();  
  26.    }  
  27.      
  28.       //關閉Session  
  29.    public static void closeSession(Session session){  
  30.        if(session!=null){  
  31.            if(session.isOpen()){  
  32.                session.close();  
  33.            }  
  34.        }  
  35.    }  
  36.      
  37.    public static SessionFactory getSessionFactory(){  
  38.        return factory;  
  39.    }  
  40. }  
  1. 用戶業務邏輯層  
  2. package com.bjpowernode.usermgr.manager;  
  3.   
  4. import java.util.Date;  
  5.   
  6. import org.hibernate.Session;  
  7.   
  8. import com.bjpowernode.usermgr.domain.Log;  
  9. import com.bjpowernode.usermgr.domain.User;  
  10. import com.bjpowernode.usermgr.util.HibernateUtils;  
  11.   
  12. public class UserManagerImpl implements UserManager {  
  13.   
  14.       /** 
  15.     * 添加用戶和添加日誌都使用了同一個Session,所以 
  16.     * 當用戶添加失敗的時候,日誌也會添加失敗。事務回滾 
  17.     * 用戶添加成功日誌也會添加成功 
  18.     */  
  19.     public void addUser(User user) {  
  20.           
  21.         Session session=null;  
  22.         try{  
  23.             //取得當前線程Session  
  24.             session=HibernateUtils.getSessionFactory().getCurrentSession();  
  25.             session.beginTransaction();  
  26.               
  27.             //保存用戶  
  28.             session.save(user);  
  29.               
  30.             Log log=new Log();  
  31.             log.setType("操作日誌");  
  32.             log.setTime(new Date());  
  33.             log.setDetail("XXX");  
  34.               
  35.             LogManager logManager=new LogManagerImpl();  
  36.             //保存日誌  
  37.             logManager.addLog(log);  
  38.               
  39.             session.getTransaction().commit();  
  40.               
  41.         }catch(Exception e){  
  42.             e.printStackTrace();  
  43.             session.getTransaction().rollback();  
  44.         }  
  45.     }  
  46.   
  47. }  
  48.   
  49. 日誌實現類:  
  50. package com.bjpowernode.usermgr.manager;  
  51.   
  52. import org.hibernate.Session;  
  53.   
  54. import com.bjpowernode.usermgr.domain.Log;  
  55. import com.bjpowernode.usermgr.util.HibernateUtils;  
  56.   
  57. public class LogManagerImpl implements LogManager {  
  58.   
  59.   
  60.     public void addLog(Log log) {  
  61.           
  62.         //獲取當前線程的Session  
  63.         HibernateUtils.getSessionFactory().getCurrentSession().save(log);  
  64.   
  65.     }  
  66.   
  67. }  
  68.   
  69. 測試類  
  70. package com.bjpowernode.usermgr.manager;  
  71.   
  72. import junit.framework.TestCase;  
  73.   
  74. import com.bjpowernode.usermgr.domain.User;  
  75.   
  76. public class UserManagerImplTest extends TestCase {  
  77.   
  78.     public void testAddUser() {  
  79.         UserManager userManager=new UserManagerImpl();  
  80.         User user=new User();  
  1.     user.setName("張三");  
  2.     userManager.addUser(user);  
  3. }  

注意:

1.openSession和getCurrentSession的區別?

   *openSession必須關閉,currentSession在事務結束後自動關閉

   *openSession沒有和當前線程綁定,currentSession和當前線程綁定

2.如果使用currentSession需要在hibernate.cfg.xml文件中進行配置:

   *如果是本地事務(jdbc事務)

     <propertyname="hibernate.current_session_context_class">thread</property>

   *如果是全局事務(jta事務)

   <propertyname="hibernate.current_session_context_class">jta</property>

全局事務:資源管理器管理和協調的事務,可以跨越多個數據庫和進程。資源管理器一般使用XA 二階段提交協議與“企業信息系統”(EIS) 或數據庫進行交互。 

本地事務:在單個 EIS或數據庫的本地並且限制在單個進程內的事務。本地事務不涉及多個數據來源。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章