hibernate 樂觀鎖

xmh_sxh_1314發表於2020-10-06

在這裡插入圖片描述

樂觀鎖採用的原理就是在表裡邊加version版本控制,

<versionname=“version”
column=“VERSION”
type=“integer”
/>

例子:

建立兩個session:

Session session1=SessionFactory.openSession();

Session session2=SessionFactory.openSession()

對同一個資料進行操作:

Entity entity1=new Entity();

Entity entity2=new Entity();

entity1=session1.load(Entity.class,id);

entity1.setName(“name1”);

entity1.setName(“name1”);
Transaction tran1 = session1.beginTransaction();
session1.close();

entity2.setName(“name2”);
Transaction tran2= session2.beginTransaction();
session2.close();

執行到後邊的tran2提交時會報異常:org.hibernate.StaleObjectStateException異常。
之所以報這個異常,就是因為我們在Entity裡邊增加了version,第一個事務提交之後version=version+1=2,而第二個事務提交時,version=1<2,就會 報這個異常,資料過時

U2FsdGVkX1+XTVardIlqVeZS7LqK6vy8uZ1InRCXi5OHtEKWSi8lsDXm9KKruUT6
9QgxbdTr8o2Av/SH0xlQjTt3jsj55I245FsvI6JOPdjSIdxwI7bApXfVQ0c9cEhR
G3aLs2jqFAYCev2lF1JxxbZzXEq76ZCfQT9wm86ZOTaOBnPTJgw/SfksiqJIiWm/
TSiliKUYf/BhqJpkAGYCQOPK4CrOYA9w+E9BVletcRklkPMNPD7hzPgJIW7BrM3N
UDKxbpGZjjFvai5PavmpBxS8gtpTi6gkp8WHp46COEHCAk7seeZK7rARsK3qMPU5
nug6T7zVIASBPYeK0hLG0jsX9n/GgUtvK0G7gY/uMqvvpMXfGMYRw0ykgAJTQgCv
X8EvGnkQr96wfxwE0e0H0geROmyfPxW6xhiDlj/PT0zEXGta3tdYZqkDh6gFRWsE
/b3jst9neUw50vpN5dlbkYJ6Nlsr4BWGzh8iUWbeE24kbloMbEzSyzv/yYCbvuBE
2QNdsOQzaL0CgMgHgnp2/QTxaaGznaf6khsx494QH8apFmzTN+sZkEOyWf4FKvIU
bJF2/2q16mvXq7iLSzORy+CG9tTPoXirTJf2N1O0vjDNec0U2gNzoODkqNBPGY0y
GrTfr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