Hibernate 悲观锁与乐观锁(2)

当两个不同的事务同时读取到一条数据并进行修改时,这个时候程序就会抛出org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)异常。 

这里同样有两种情况 

一种是两个不同的事务的情况 

@Test public void testTransation1(){ Session session1 = null; Session session2 = null; try{ session1 = HibernateUtil.getSession(); session2 = HibernateUtil.getSession(); Info info1= session1.load(Info.class, "p003"); Info info2 = session2.load(Info.class, "p003"); Transaction tx1 = session1.beginTransaction(); info1.setName("2222222"); tx1.commit(); Transaction tx2 = session2.beginTransaction(); info2.setName("11111111"); tx2.commit(); System.out.println("事务2提交"); }catch(Exception e){ e.printStackTrace(); }finally{ if(session1 != null){ session1.close(); } if(session2 != null){ session2.close(); } } }

事务2提交时发现version的值不一样,这个时候就会抛出org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)异常.

第二种情况是子事务的情况 

@Test public void testTransation2(){ Session session1 = null; Session session2 = null; try{ session1 = HibernateUtil.getSession(); session2 = HibernateUtil.getSession(); Info info1= session1.load(Info.class, "p003"); Info info2 = session2.load(Info.class, "p003"); Transaction tx1 = session1.beginTransaction(); Transaction tx2 = session2.beginTransaction(); info2.setName("11111111"); tx2.commit(); info1.setName("2222222"); tx1.commit(); }catch(Exception e){ e.printStackTrace(); }finally{ if(session1 != null){ session1.close(); } if(session2 != null){ session2.close(); } } }

解决办法

1、捕获StaleObjectStateException异常,提示数据过时已被修改,让用户重新提交

2、尽量从业务方面去减小事务块,事务块越大,由乐观锁引起的问题的概率就越大

Hibernate3.1.2_中文文档PDF 

Hibernate学习入门教程 

在Hibernate中开启日志

Hibernate+JUnit测试实体类生成数据库表 

Hibernate整体理解

Hibernate的映射机制 

Hibernate利用@DynamicInsert和@DynamicUpdate生成动态SQL语句 

Struts2+Spring3+Hibernate3+MySQL简单登录实现 

Hibernate的简单示例 

Intellij IDEA 15 下新建 Hibernate 项目及添加配置 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/df6b39d23b7c9e2e3880753bfbd16759.html