11

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?

Dayton Tex
  • 754
  • 3
  • 8
  • 17

2 Answers2

9

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

Community
  • 1
  • 1
gerrytan
  • 37,387
  • 8
  • 78
  • 91
  • 2
    I know how to catch exceptions :) The problem is that a different exception is being thrown here. As I read in documentation and books, OptimisticLockException should be thrown in the case of optimistic concurrency. I'm getting StaleObjectStateException instead. I want the other one! :D – Dayton Tex Aug 12 '13 at 15:57
  • 1
    StaleObjectStateException is thrown when you use straight hibernate API. OptimisticLockException is if you used JPA style hibernate. If this confuses you please read: http://stackoverflow.com/questions/9881611/whats-the-difference-between-jpa-and-hibernate – gerrytan Aug 13 '13 at 05:58
  • I've posted a question [here](https://stackoverflow.com/questions/50001990/hibernate-staleobjectstateexception-issue-calling-merge/50002168#50002168) which uses JPA and i'm still getting a StaleObjectStateException. Can you please clarify your answer? – Orby Apr 25 '18 at 07:59
1

As of my analysis of Hibernate 3.5.2 (now bit old), I found they sometimes throw OptimisticLockException and sometimes StaleObjectStateException. Batch operations even throw StaleStateException, which is a superclass of StaleObjectStateException, but don't have the entity instance.

It seems to me as an unfinished refactoring, you probably need to catch both and react to both the same way.

Oliv
  • 8,930
  • 2
  • 43
  • 70