Topquan's Blog

          分享價(jià)值----成就你我----我的博客----你的家

          hibernate事務(wù)處理和鎖

          事務(wù)處理:
          Hibernate本身并不具備事務(wù)管理能力。在事務(wù)管理層,Hibernate將其委托給底層的JDBC或者JTA,以實(shí)現(xiàn)事務(wù)的管理與調(diào)度。

          基于JDBC的事務(wù):
          無(wú)疑是最簡(jiǎn)單的實(shí)現(xiàn)方式,
          session = sessionFactory.openSession();
          Transaction tx = session.beginTransaction();
          tx.commit();

          基于JTA的事務(wù)管理:
          hibernate默認(rèn)采用JDBC Transacion。可以通過(guò)配置文件指定采用JTA作為事務(wù)管理實(shí)現(xiàn)。
          <hibernate-configuration>
              <session-factory>
                  ......
                  <property name="hibernate.transaction.factory_class">
            org.hibernate.transaction.JTATransactionFactory
                  </property>
              </session-factory>
          </hibernate-configuration>

          鎖(locking)
          支持兩種鎖:悲觀鎖和樂(lè)觀鎖

          悲觀鎖(Pessimistic locking):
          數(shù)據(jù)庫(kù)的實(shí)現(xiàn)
          select * from account where name='yyy' for update
          通過(guò)for update子句,這條語(yǔ)句鎖定所有符合條件的記錄,在本次事務(wù)提交之前,外界無(wú)法修改這些記錄。

          hibernate的實(shí)現(xiàn),也是基于數(shù)據(jù)庫(kù)的鎖機(jī)制實(shí)現(xiàn):
          加鎖一般通過(guò)以下方法實(shí)現(xiàn):
          Criteria.setLockMode
          Query.setLockMode
          Session.lock

          hibernate的加鎖模式:
          LockMode.NONE:無(wú)鎖機(jī)制
          LockMode.WRITE:hibernate在Insert和update時(shí),會(huì)自動(dòng)獲取
          LockMode.READ:hibernate在讀取記錄的時(shí)候,會(huì)自動(dòng)獲取
          以上3種,由hibernate內(nèi)部使用。

          LockMode.UPGRADE:利用數(shù)據(jù)庫(kù)的for update子句加鎖
          LockMode.UPGRADE_NOWAIT:oracle特定實(shí)現(xiàn),利用oracle的for update nowait子句實(shí)現(xiàn)加鎖。

          樂(lè)觀鎖(Optimistic locking):
          hibernate在其數(shù)據(jù)訪問(wèn)引擎中內(nèi)置了樂(lè)觀鎖實(shí)現(xiàn)。可以通過(guò)class描述符的optimistic-lock屬性結(jié)合version描述符指定。

          <hibernate-mapping>
              <class
                  name="org.hibernate.sample.TUser"
                  table="t_user"
                  dynamic-update="true"
                  dynamic-insert="true"
                  optimistic-lock="version"
              >
               <id>......
               </id>
                <version
                   column="version"
                   name="version"
                   type="java.lang.Integer"
                />
              </class>
          </hibernate-mapping>
          注意,version節(jié)點(diǎn)要在ID節(jié)點(diǎn)之后。
          這里,聲明了一個(gè)version屬性,用于存放用戶的版本信息,保存在T_User表的version字段中。

          posted on 2006-08-05 01:18 topquan 閱讀(2678) 評(píng)論(0)  編輯  收藏 所屬分類: Hibernate

          主站蜘蛛池模板: 电白县| 长沙县| 元江| 浑源县| 洛浦县| 化州市| 信丰县| 二连浩特市| 雷州市| 麻栗坡县| 乌兰浩特市| 随州市| 油尖旺区| 墨脱县| 桃园市| 扎兰屯市| 宜兴市| 桐城市| 霍邱县| 锡林浩特市| 宜昌市| 黑水县| 迁西县| 日喀则市| 平江县| 石台县| 瑞昌市| 湛江市| 西乌珠穆沁旗| 同江市| 麻阳| 丹巴县| 屏边| 开江县| 交口县| 萍乡市| 勐海县| 甘德县| 吕梁市| 佳木斯市| 即墨市|