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


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章