java多線程使用HibernateSession 時報 No session 的解決辦法

來源:互聯網
上載者:User

標籤:

服務端新開多線程使用HibernateSession 杜絕No session

新起的線程需要綁定Hibernate session,才能在新線程中使用事務和消極式載入等功能,否則會曝出no session異常;

解決辦法:

 

[java] view plaincopy 
  1. new Runnable() {  
  2.                 @Override  
  3.                 public void run() {  
  4. //                  ----------綁定session到當前線程------------  
  5.                     SessionFactory sessionFactory = (SessionFactory)applicationContext.getBean("sessionFactory");  
  6.                     boolean participate = ConcurrentUtil.bindHibernateSessionToThread(sessionFactory);  
  7. //                  ---------你的業務---------------  
  8. <pre name="code" class="java">//                  ----------關閉session------------                     
  9.                     ConcurrentUtil.closeHibernateSessionFromThread(participate, sessionFactory);  
  10.                 }  
  11.                   
  12.             }  

 

bindHibernateSessionToThread方法:

 

 

[java] view plaincopy 
  1. public static boolean bindHibernateSessionToThread(SessionFactory sessionFactory) {  
  2.     if (TransactionSynchronizationManager.hasResource(sessionFactory)) {  
  3.         // Do not modify the Session: just set the participate flag.  
  4.         return true;  
  5.     } else {  
  6.         Session session = sessionFactory.openSession();  
  7.         session.setFlushMode(FlushMode.MANUAL);  
  8.         SessionHolder sessionHolder = new SessionHolder(session);  
  9.         TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);  
  10.     }  
  11.     return false;  
  12. }  

closeHibernateSessionFromThread方法

 

 

[java] view plaincopy 
  1. public static void closeHibernateSessionFromThread(boolean participate, Object sessionFactory) {  
  2.   
  3.     if (!participate) {  
  4.         SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.unbindResource(sessionFactory);  
  5.         SessionFactoryUtils.closeSession(sessionHolder.getSession());  
  6.     }  
  7. }  

 

事務邊界則由aop或者Transactional標記來控制,範例程式碼只是保證具備事務性的方法在需要的時候能從當前線程中獲得session對象。

上述代碼大部分截取自Spring的OpenSessionInViewFilter。

java多線程使用HibernateSession 時報 No session 的解決辦法(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.