[轉]OpenSessionInView模式

來源:互聯網
上載者:User

標籤:

OpenSessionInView模式解決的問題:
  * hibernate事物邊界問題
  * 因session關閉導致hibernate消極式載入例外的問題

事物邊界:
    一個事物的完成應該是在業務層完成的,但是事物的建立卻是在資料層來做,這樣必定造成業務層和資料層耦合性增強。

消極式載入例外:
     如你所知,消極式載入使用了動態代理機制,只有在真正使用這個對象的時候才會去訪問資料庫,但是如果在資料層進行了事物提交,session關閉,再去訪問資料就會導致消極式載入例外異常,所以我們必須加大session的生命週期,在訪問資料之後關閉session。

因此我們可以通過OpenSessionInView模式來解決上面的問題


OpenSessionInView模式需要用到一個非常重要的一個類:ThreadLocal

OpenSessionInView模式:
  * 需要構建一個過濾器,把事物的建立及提交放在過濾器裡進行。
  * 加大session的有效範圍,把session放在當前線程裡(ThreadLocal),使session在當前線程內有效,並且在當前線程內訪問的是同一個session。

OpenSessionInView模式缺點:
  *並發性減弱
  *記憶體消耗加大

1.實體類:
Java代碼  
  1. package com.yx.zzg.pojo;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class User {  
  6.       
  7.     private String id;  
  8.   
  9.     private String username;  
  10.   
  11.     private String password;  
  12.   
  13.     private Date createTime;  
  14.   
  15.     private Date endTime;  
  16.   
  17.     public String getId() {  
  18.         return id;  
  19.     }  
  20.   
  21.     public void setId(String id) {  
  22.         this.id = id;  
  23.     }  
  24.   
  25.     public String getUsername() {  
  26.         return username;  
  27.     }  
  28.   
  29.     public void setUsername(String username) {  
  30.         this.username = username;  
  31.     }  
  32.   
  33.     public String getPassword() {  
  34.         return password;  
  35.     }  
  36.   
  37.     public void setPassword(String password) {  
  38.         this.password = password;  
  39.     }  
  40.   
  41.     public Date getCreateTime() {  
  42.         return createTime;  
  43.     }  
  44.   
  45.     public void setCreateTime(Date createTime) {  
  46.         this.createTime = createTime;  
  47.     }  
  48.   
  49.     public Date getEndTime() {  
  50.         return endTime;  
  51.     }  
  52.   
  53.     public void setEndTime(Date endTime) {  
  54.         this.endTime = endTime;  
  55.     }  
  56. }  


2.對應檔:
Java代碼  
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC   
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping package="com.yx.zzg.pojo">  
  6.     <class name="User" table="t_user">  
  7.         <id name="id">  
  8.             <!-- 指定主鍵建置原則 -->  
  9.             <generator class="uuid" />  
  10.         </id>  
  11.         <property name="username" unique-key="true" />  
  12.         <property name="password" />  
  13.         <property name="createTime" />  
  14.         <property name="endTime" />  
  15.     </class>  
  16.   
  17. </hibernate-mapping>  


3.提供一個過濾器:
Java代碼  
  1. package com.yx.zzg.servelt;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.Filter;  
  6. import javax.servlet.FilterChain;  
  7. import javax.servlet.FilterConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletRequest;  
  10. import javax.servlet.ServletResponse;  
  11.   
  12. import org.hibernate.Session;  
  13. import org.hibernate.Transaction;  
  14.   
  15. import com.yx.zzg.util.HibernateUtil;  
  16.   
  17. public class OpenSessionInView implements Filter {  
  18.   
  19.     public void destroy() {  
  20.   
  21.     }  
  22.   
  23.     public void doFilter(ServletRequest request, ServletResponse response,  
  24.             FilterChain filter) throws IOException, ServletException {  
  25.         Transaction tx = null;  
  26.         Session session = null;  
  27.         try {  
  28.             session = HibernateUtil.getThreadLocalSession();  
  29.             tx = session.beginTransaction();  
  30.             filter.doFilter(request, response);  
  31.             tx.commit();  
  32.         } catch (Exception e) {  
  33.             if (tx != null) {  
  34.                 tx.rollback();  
  35.                 throw new RuntimeException(e.getMessage(),e);  
  36.             }  
  37.         } finally {  
  38.             HibernateUtil.colseSession();  
  39.         }  
  40.     }  
  41.   
  42.     public void init(FilterConfig arg0) throws ServletException {  
  43.   
  44.     }  
  45.   
  46. }  


4.web.xml中配置過濾器
Java代碼  
  1. <filter>  
  2.         <filter-name>OpenSessionInView</filter-name>  
  3.         <filter-class>com.yx.zzg.servelt.OpenSessionInView</filter-class>  
  4.     </filter>  
  5.     <filter-mapping>  
  6.         <filter-name>OpenSessionInView</filter-name>  
  7.         <url-pattern>/*</url-pattern>  
  8.     </filter-mapping>  


5.HibernateUtil類:
Java代碼  
  1. package com.yx.zzg.util;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6.   
  7. public class HibernateUtil {  
  8.       
  9.     private static SessionFactory sessionFactory;  
  10.   
  11.     //建立一個ThreadLocal對象  
  12.     private static ThreadLocal threadSession = new ThreadLocal();  
  13.   
  14.     private HibernateUtil() {  
  15.   
  16.     }  
  17.   
  18.     static {  
  19.         Configuration cfg = new Configuration().configure();  
  20.         sessionFactory = cfg.buildSessionFactory();  
  21.     }  
  22.   
  23.     /** 
  24.      * 從當前線程中擷取session,如果沒有,則得到session,並將此session放入當前線程中 
  25.      * @return 
  26.      */  
  27.     public static Session getThreadLocalSession() {  
  28.         Session session = (Session) threadSession.get();  
  29.         if (session == null) {  
  30.             session = getSession();  
  31.             threadSession.set(session);  
  32.         }  
  33.         return session;  
  34.     }  
  35.   
  36.     /** 
  37.      * 關閉session,並將當前線程中的session設定為null 
  38.      */  
  39.     public static void colseSession() {  
  40.         Session session = (Session) threadSession.get();  
  41.         if (session != null) {  
  42.             session.close();  
  43.             threadSession.set(null);  
  44.         }  
  45.     }  
  46.   
  47.     public static Session getSession() {  
  48.         return sessionFactory.openSession();  
  49.     }  
  50.   
  51. }  


6.資料層方法:
Java代碼  
  1. public User findUserById(String id) {  
  2.     User user = (User) HibernateUtil.getThreadLocalSession().load(  
  3.             User.class, id);  
  4.     return user;  
  5. }  

[轉]OpenSessionInView模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.