且构网

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

StaleObjectStateException VS OptimisticLockException

更新时间:2023-12-05 14:48:22

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

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?

使用try catch块捕获异常:

Use try catch block to catch the exception:

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

这是值得注意的OptimisticLockException发生,因为其他事务更新(因此创建的更新版本)的对象之前,你有机会这样做。在UI应用程序中,通常提示用户是否覆盖/丢弃/合并他/她的对象版本

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