Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StaleObjectStateException vs OptimisticLockException

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?

like image 600
Dayton Tex Avatar asked Aug 11 '13 21:08

Dayton Tex


1 Answers

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

like image 145
gerrytan Avatar answered Sep 21 '22 18:09

gerrytan