Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best update strategy on hibernate stalestateException

we are using hibernate with optimistic locking. All our entities have the @version annotation.

This works fine, if a user tries to save an object that is stale we get a stalestateexception. In our case we would like to give the user a notification screen to discard his changes or overwrite the current values in the database.

This a common use case for stale state exceptions. My question is related to this use case. What is the best strategy if the user decides to overwrite the current database row with his changes? I've gone through the hibernate reference guide and different websites but all that is mentioned there is the fact that you have to catch the stalestateexception yourself and then programmaticaly handle the overwrite of the data. I'm wondering if hibernate has some utilities to simplify this strategy, simplest thing i can get up with if the user decides to overwrite with his data is retrieving the last version of the entity from the database then copying all changed fields to this object and then saving the changed object back to the database. But i can't stop wondering if there isn't a more elegant solution.

like image 713
Peter Bierman Avatar asked Jan 12 '12 08:01

Peter Bierman


1 Answers

I don't think Hibernate will attempt to help you with this because requirements in this area are likely to be very complex and bespoke.

I am guessing that if a user were to save an object which has been simultaneously changed by another user you most likely won't want to simply load the object and copy all of the changed fields and undo all the other users changes. What happens if both users changed the same field? You wmight want to present the two versions to the user and ask them to decide which version is correct. A bit like merging changes in a version control system.

Also you might have UI level validation which links fields which could be violated if you simply merge two versions of the same entity in the back end and persist it.

like image 172
Alex Barnes Avatar answered Oct 01 '22 15:10

Alex Barnes