在这里插入图片描述
乐观锁采用的原理就是在表里边加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+aKy/tUvJGXsJhsgZIFL91nEADKb+JIOnK0XZ8jWc/8vEG/ZjYCs7l
s1bh1g/1fegnHvASC1CawIbj6eMIotAknc1b5o2kqIKTtyOikwlwa3cM22tL9Fn8
MwVUiPRHQUzi7n/MNR5ZM1wQ2n1ilzy0vPKZfzTUcy7yL/hR3xo2ZY/F3e9J4WUB
+sPIvB/vam8Df3kJCLQOElqd9KOj0t3Vi2hBn24O0aKHiQXKLLyaNCzPtCCGxUC6
TCwt8L9I8iqROS/Uy6uusjD1Y2+KjsWWnPAdTj+SDfQM8O9x3H2CYaGN55lIQT4S
vtp30qJYLy5EbG1ejNBiGVEbpeKeyAAtX55TdFQBqm4InGTTG7e1p7vdYVD8Or2u
NKZha2WWPLUaE8arcXOG/73YlfVP9cDtz6KATwLg6BR8E1vp+lSEsWRxW5atTIbp
N2c2tq9Bf88ZVkD4SF6kkkxcJpp+1i67vTCwf1qZ4bc3AgcYRPGTcJ07bX+kQEeX
erUxfJyOVZ62OWubUfY5jr0MxHvNA6SOXbFeq+xzc9LXyQysKCcfelU57tJ9Wnjn
oMBOGypEuix9KHarc8qZf8+f2o9NDnEBn/G3PIJs/yNMUaUyksCNYe8yD15kuUcJ
N8FIkboWylSNqpjo4IjC2qPGgkv3Stf6JAuwVxFibo7/kIndMoaTJE4/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BHMwgi49mSuciybkof1t3FLohJlylxO/sJhxZD+kJgLX
AslAvfZ5BBn44jWd9Tks/qgb83+rB2UDZFlz/nsqiPHRA3hBgOWznt3UUpuRjGZH
ASAa2pgqRtmXCQDOZvJBcJDR65WGvYxOL3b6c92H9QJvDWzZTSZ8u3yVZqzA5/zd
wBd/E76TQRqeFbZCFP2DE492PxZP5OWBcCcoRVldLgYWd1wosiB4ZCFcOkFilaEO
4IGEBL9mYtBnayCjWyLB6nlphXmiE5uwmoQAwYK7NBgHOx/aeXoBg7TeyTiIm/re
nJpV1oWmoBGBPZoCmaRdUFYp43/IZ9sT1HTP36jRqYmYn6MI5qyo+9nBw0YgAqd3
FC8+DNMqbTGqcYh5zcs4tkl78QpYqkzkvp++MDcm5mO6tncA9bBuoeOLd148Nf1j
dxrsu01XhSBqNb7nDt0e518vw9FbJMskLiYWpaoDP5RbOljczOVerRoTDn/pANsV
KBcvtOiY6Jy68SfvScG3k8uORERSZClps3qQz8Es01+egB8yLUOkKqdUDlPg7h78
45iLt8Qi2u/8Pv6eulzpmLJSG6+LXn/GAA7UuwkLr4cz/NFAADnGij+A7r9kh9Cs
BadGCGetgu3fBKOUt/bbQ4crk7mRS58gR8DAiqDEGVQZWnnWM3tRcLh4sFKRzM4b
rqcTgg0em4aztyw2eF9pRgRb+poaU1sWzQCmQ/IkKByW1VPdACf2sARxiCu7E3Vu
LmUgNLmq+oPuIXDrx6jQM78WqVyvJ9zMwv9BxFFlFJrUs0G7JW5OYbkUwIyHSkUv
GRmopbTSVC5cz3cPaXBQEft6MOqDs4xQvL8H6AIg5QZzds+SBviGXQKg181ePWDx
MsK+9/mYI6JksmxW5wHgghcZ/NkL5sAl1md3+gJvALhah3ksh9EmMX4rYmvvlvon
umW9HmBaKFTDvCAvTNPWlWPFka6ShIL8gNt15h5FT05RiJRxWF+Zk9QWk7U5InYb
ol29UwvququfgvAyySNR3rfotwg8WsOXwiF9d2g5k40=

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐