posts - 3,  comments - 12,  trackbacks - 0

          通過在表中及POJO中增加一個version字段來表示記錄的版本,來達到多用戶同時更改一條數據的沖突

          數據庫腳本:

           

          create table studentVersion (id varchar(32),name varchar(32),ver int);

          POJO

           

          package Version;

          public class Student {
            
          private String id;
            
          private String name;
            
          private int version;
          public String getId() {
              
          return id;
          }

          public void setId(String id) {
              
          this.id = id;
          }

          public String getName() {
              
          return name;
          }

          public void setName(String name) {
              
          this.name = name;
          }

          public int getVersion() {
              
          return version;
          }

          public void setVersion(int version) {
              
          this.version = version;
          }



          }

           

          Student.hbm.xml

           

          <?xml version="1.0" encoding="utf-8"?>
          <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
          >
          <!-- 
              Mapping file autogenerated by MyEclipse - Hibernate Tools
          -->
          <hibernate-mapping>
          <class name="Version.Student" table="studentVersion" >
              
          <id name="id" unsaved-value="null">
                
          <generator class="uuid.hex"></generator>
              
          </id>
              
          <!--version標簽必須跟在id標簽后面-->
              
          <version name="version" column="ver" type="int"></version>
              
          <property name="name" type="string" column="name"></property>  
          </class>

          </hibernate-mapping>

           

          Hibernate.cfg.xml

           

          <?xml version='1.0' encoding='UTF-8'?>
          <!DOCTYPE hibernate-configuration PUBLIC
                    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
          >

          <!-- Generated by MyEclipse Hibernate Tools.                   -->
          <hibernate-configuration>

          <session-factory>
              
          <property name="connection.username">root</property>
              
          <property name="connection.url">
                  jdbc:mysql://localhost:3306/schoolproject?characterEncoding=gb2312
          &amp;useUnicode=true
              
          </property>
              
          <property name="dialect">
                  org.hibernate.dialect.MySQLDialect
              
          </property>
              
          <property name="myeclipse.connection.profile">mysql</property>
              
          <property name="connection.password">1234</property>
              
          <property name="connection.driver_class">
                  com.mysql.jdbc.Driver
              
          </property>
              
          <property name="hibernate.dialect">
                  org.hibernate.dialect.MySQLDialect
              
          </property>
              
          <property name="hibernate.show_sql">true</property>
              
          <property name="current_session_context_class">thread</property>
              
          <property name="jdbc.batch_size">15</property>
              
          <mapping resource="Version/Student.hbm.xml" />




          </session-factory>

          </hibernate-configuration>

           

          測試代碼:

           

          package Version;


          import java.io.File;
          import java.util.Iterator;
          import java.util.Set;

          import org.hibernate.Session;
          import org.hibernate.SessionFactory;
          import org.hibernate.Transaction;
          import org.hibernate.cfg.Configuration;

          public class Test {


              
          public static void main(String[] args) {

                  String filePath
          =System.getProperty("user.dir")+File.separator+"src/Version"+File.separator+"hibernate.cfg.xml";
                  File file
          =new File(filePath);
                  System.out.println(filePath);
                  SessionFactory sessionFactory
          =new Configuration().configure(file).buildSessionFactory();
                  Session session
          =sessionFactory.openSession();
                  Transaction t
          =session.beginTransaction();
                  
                  Student stu
          =new Student();
                  stu.setName(
          "tom11");
                  session.save(stu);
                  t.commit();
                
                  
                  
          /*
                   * 模擬多個session操作student數據表
                   
          */

                  
                  Session session1
          =sessionFactory.openSession();
                  Session session2
          =sessionFactory.openSession();
                  Student stu1
          =(Student)session1.createQuery("from Student s where s.name='tom11'").uniqueResult();
                  Student stu2
          =(Student)session2.createQuery("from Student s where s.name='tom11'").uniqueResult();
                  
                  
          //這時候,兩個版本號是相同的
                  System.out.println("v1="+stu1.getVersion()+"--v2="+stu2.getVersion());
                  
                  Transaction tx1
          =session1.beginTransaction();
                  stu1.setName(
          "session1");
                  tx1.commit();
                  
          //這時候,兩個版本號是不同的,其中一個的版本號遞增了
                  System.out.println("v1="+stu1.getVersion()+"--v2="+stu2.getVersion());
                  
                  Transaction tx2
          =session2.beginTransaction();
                  stu2.setName(
          "session2");
                  tx2.commit();
                  
                  
                  
              }


          }

           

          運行結果:

          Hibernate: insert into studentVersion (ver, name, id) values (?, ?, ?)
          Hibernate: select student0_.id as id0_, student0_.ver as ver0_, student0_.name as name0_ from studentVersion student0_ where student0_.name='tom11'
          Hibernate: select student0_.id as id0_, student0_.ver as ver0_, student0_.name as name0_ from studentVersion student0_ where student0_.name='tom11'
          v1=0--v2=0
          Hibernate: update studentVersion set ver=?, name=? where id=? and ver=?
          v1=1--v2=0
          Hibernate: update studentVersion set ver=?, name=? where id=? and ver=?
          Exception in thread "main" org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [Version.Student#4028818316cd6b460116cd6b50830001]

           

          可以看到,第二個“用戶”session2修改數據時候,記錄的版本號已經被session1更新過了,所以拋出了紅色的異常,我們可以在實際應用中處理這個異常,例如在處理中重新讀取數據庫中的數據,同時將目前的數據與數據庫中的數據展示出來,讓使用者有機會比較一下,或者設計程序自動讀取新的數據

           

          注意:如果手工設置stu.setVersion()自行更新版本以跳過檢查,則這種樂觀鎖就會失效,應對方法可以將Student.java的setVersion設置成private

          posted on 2010-06-04 23:37 [ 王志偉 ] 閱讀(264) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          常用鏈接

          留言簿(1)

          隨筆檔案(3)

          文章檔案(29)

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 五家渠市| 当涂县| 淮阳县| 吉水县| 深圳市| 新乐市| 湘潭市| 屯留县| 鄂尔多斯市| 高州市| 开封县| 沈丘县| 秦安县| 阿瓦提县| SHOW| 东台市| 武宁县| 平阴县| 周至县| 会泽县| 那坡县| 望城县| 宝山区| 芷江| 洛隆县| 巧家县| 建平县| 司法| 开封市| 永平县| 宾川县| 玉田县| 漯河市| 阿勒泰市| 将乐县| 澄迈县| 甘泉县| 崇文区| 乌兰浩特市| 弥渡县| 汕尾市|