hibernate 乐观锁
作者:互联网
乐观锁采用的原理就是在表里边加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/DmJ4cHY3C0Aga61TsCCrUT1tkVa0SXQAGYnG1xgzFlUT+1j0kquld
u06hqtOGoKP9V8KHDOtyze+/2BuLJcOBityS7Tmgyqe8OTUtIXxPvwda1d0gqwdc
9OpiPYqXOrO/wC/BWtrCG//L61mWZGPWUFEMM64rgNaHyaBuzW9zfSBUaSi73fBY
4NS4+PghrjsAb+nj3GeHC0ShViGa5aVVL+JrSqGZUEje0AVoQxkmwlLQ0xXY1XZc
3Cgyqa5orIpLOFbs1o8Fslm3Dj5cN9yMaInyB5Jkue4MeuPLYqEoxqZFS/ZS6R2H
mjHqUKLE3HSED2VWTNd1nHauP9joa/yIty+F0l1Qmg+Y/hVFdoEnHgciD27QIs0u
4F1jBc8ut664Kay3vW6FG4BLm6ejppXICyooEukIlTs+2DejxqQD7Ad+NMQdBdxv
MzoNAxnSDivCPMn/pZkxAymOBlMJO5lf/V4tuGQ0UJMT/nQ5hzCtbZKuHU07sOkD
9gyOFRs7EtLYMg+YSoZi0j3cMVBtZdiiqfcyLOnMBEaYzScgp9GQW+DdOAgtEIn4
bEdrREd/+zJoJi/yiLSuYRf+hk3xbxckMN3vcnacgcTb1bz6sxGeMZLnFUJ1Xr+u
tygUFVgeOM9mmfNEQyuAu10xZyz322r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rFcPPK2Aw1kCivdxHQ44VL31QGCDdxfmEDfWiG84KV4/hu8iD
m4aueqVO0ISybcnZvnN7HZavR5IEqZHqR7x3SRXJaLPPT2wlY1wCCIBSnOrgKC6Q
VvSg3GGY7QaaW/qmxBHJSWlPFO5cDqnNsBAVimCxptkdFZ3gEaCvupE8of7iQEr3
RIA9CGE8kz/A56IyqrhKqTHsd0h6nupIxfdQk2n228kqIoNXwJ7EnXQhMGKoQJne
/8n2WFoeN1dKBrYrU76+sSqn2I47Hw4+N5GQPEoqdi8=
标签:hibernate,setName,session1,session2,entity1,Entity,乐观,version 来源: https://blog.csdn.net/xmh_sxh_1314/article/details/112443125