HibernateOptimisticLockingFailureException

转自: http://hi.baidu.com/putin_/item/2557103302fa66302e20c4ce

参考: http://forum.spring.io/forum/spring-projects/data/24174-hibernateoptimisticlockingfailureexception


今天用 getHibernateTemplate().saveOrUpdateAll(list); 时报如下错误,

org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

查找原因发现是hibernate乐观锁出了问题,我的应用在由于频繁调用数据库,导致有时会不能批量插入数据,

这是主要的原因:The error occurs because at least 2 transactions are working on the same record(s). If a record is read by 2 transactions, and if the record is saved by one transaction first, and then by the second one, an optimistic locking exception is thrown in the second transaction, because the assumption that nobody else was going to modify the record, doesn't hold. (Optimistic locking = You are optimistic about the facts that nobody else is going to need the same record)

解决方法:

1) make sure (by design) that records that are going to be updated, are touched by only a single transaction at any given moment


2) instead of optimistic locking, use pessimistic locking (problem: reduces scalability, and added complexity in application) 用悲观锁
3) retry the transaction: make sure that no non-transactional state is kept between retries. 出异常后重试一下。

对hibernate的乐观锁和悲观锁小结一下:
悲观锁的实现依靠数据库提供的锁机制(只有数据库层提供的锁机制才能真正的保证数据访问的排他性),这样就会大大增加
数据库性能的开销。
乐观锁大多是基于数据版本实现,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值