关于事务嵌套

  1. package com.censoft.portlets.db.base;   
  2. import com.censoft.portlets.db.DbTools;   
  3. import net.sf.hibernate.*;   
  4. import net.sf.hibernate.cfg.*;   
  5. public class HibernateSession {   
  6.   
  7.   public static final ThreadLocal sessionContext = new ThreadLocal();;   
  8.   private Session session;   
  9.   private int level;   
  10.   
  11.   public static Session currentSession(String cfgFilePath); throws Exception {   
  12.     HibernateSession hSession = (HibernateSession);sessionContext.get();;   
  13.     if (hSession == null);   
  14.     {   
  15.         hSession = new HibernateSession();;   
  16.         SessionFactory factory = DbTools.getSessionFactory(cfgFilePath);;   
  17.         hSession.session = factory.openSession();;   
  18.         hSession.level = 0;   
  19.         sessionContext.set( hSession );;   
  20.     }   
  21.     hSession.level++;   
  22.     return hSession.session;   
  23.   }   
  24.   
  25.   public static void closeSession(); throws Exception {   
  26.     HibernateSession hSession = (HibernateSession);sessionContext.get();;   
  27.     if (hSession == null);   
  28.     {   
  29.         return;   
  30.     }   
  31.     hSession.level--;   
  32.     if (hSession.level <= 0);   
  33.     {   
  34.         if (hSession.session != null && hSession.session.isOpen(););   
  35.         {   
  36.             hSession.session.close();;   
  37.         }   
  38.         sessionContext.set( null );;   
  39.     }   
  40.   }   
  41.   
  42. }  
  43. 码并不是nested transaction只是在同一个线程里只使用一个session对象。事务嵌套是一种概念,SUN的J2EE规范的确没有实现事务嵌套。但其实我们使用flat transaction其实也已经足够了。
  44. 这种做法有点象COM里引用计数。
    我在想,事实业务中是否需要嵌套事务。如果可能的话,尽量把做法向简单那里靠。
原文地址:https://www.cnblogs.com/anuoruibo/p/2410211.html