且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

StaleObjectStateException与OptimisticLockException

更新时间:2023-12-05 15:01:46

当您使用直接的hibernate API时,会抛出StaleObjectStateException异常。如果您使用JPA风格的hibernate,则会抛出OptimisticLockException异常。如果这让您感到困惑,请阅读: JPA和Hibernate之间有什么区别?



使用try catch块来捕获异常:

  try {
//你的hibernate操作这里
} catch(OptimisticLockException e){
//做某事(例如:通知用户更新冲突)
}

A StaleObjectStateException is being thrown in my app instead of OptimisticLockException (as I read I should expect this one) when optimistic concurrency problem occurs in my app. No need to post code, as it's the most basic concurrency problem - wrong version in a timestamp column.

How am I supposed to get OptimisticLockException, not the other one?

StaleObjectStateException is thrown when you use straight hibernate API. OptimisticLockException is thrown if you used JPA style hibernate. If this confuses you please read: What's the difference between JPA and Hibernate?

Use try catch block to catch the exception:

try {
  // your hibernate operation here
} catch (OptimisticLockException e) {
  // do something (eg: inform user update is conflicting)
}

It's worth noting OptimisticLockException occur due to other transaction has updated (hence created newer version of) the object before you got chance to do so. In a UI application it is common to prompt the user whether to overwrite / discard / merge his/her version of the object