• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HibernateOptimisticLockingFailureException, why?

 
Jennifer Zhen
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

This is my scenario:

I got one Address to be saved as a new record, calling saveorupdate and flush. Didn't commit though, since session per request pattern would commit at the end.

In another method in the same request, the address was regained using getById() and updated for one more field calling update(). When flushing, I got this HibernateOptimisticLockingFailureException.

Question:

Why have I got the HibernateOptimisticLockingFailureException since each update was on the latest values (I checked through setting breakpoints). I assume this exception only happens if two updates all happen on the same retrieved instance , i.e., if the version numbers are the same? Since the two updates were all on latest values, the version numbers should also be different.

Any idea?
 
Anantha Sharma
Ranch Hand
Posts: 43
Android Hibernate jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The error occurs because there are 2 transactions working on the same record. If a record is read by 2 transactions, and if the record is saved by one transaction first (in your case the call to saveorupdate()), and then by the second one (update after the getId() call), an optimistic locking exception is thrown in the second transaction, because the system assumes that nobody else is going to modify the record.
 
Jennifer Zhen
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thank you Anantha for your answer.

The fact is I think I am having only one transaction. While, the two calls were indeed in two transactions, however, both transactions were wrapped in one big request scope transaction. Since the first two "small" transactions were having "Required" propagation scope, wouldn't they all join the outer transaction?

I am still puzzled about this exception...
 
Anantha Sharma
Ranch Hand
Posts: 43
Android Hibernate jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
since the propagation is Required, the application will not continue unless there is a transaction, this means there are 2 transactions (as you pointed out), the exception is due to both the transactions trying to obtain a lock at the same time...

its always better to
1. read all necessary data
2. do app processing
3. then save the data (this is where you would require a writable transaction).

if you modify the object after writing to it & have another transaction working with this object, there is a good chance of you getting the same exception again ..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic