Originally posted by Vinays Singhh:
Hi
ALtgh this is not directly related to exam but this is a question for all the architects/designers.
How would we manage the famous "lost Update" situation in web applications ? The situation : There are two instances A & B working with same set of data or same row in table. Both are viewing the data and now both press edit button. The data is displayed to them and both press update after making some changes.
The person who pressed last , only his data would be updated in the system.
To avoid this we can't lock the row when person is editing,as in web situation we never know when he would press update.
How can we manage this in web applications?
Thanks
Vinay
Pretty easy. This is called
optimistic locking. It's explained in many books (i.e. - "Patterns of Enterprise Applications Architecture", "Hibernate in Action", "Data Access Patterns", etc., etc., etc.!) and in many articles in the net.
The simplest variant can be implemented using
versioning.
You will need to keep
version field with each database row. Each time you are updating it, you will increment 'version'.
Just like in below example.
You show to user page with data which he can modify. As a hidden field you are keeping 'version' (for example it is equal to 10). In next action where you are doing SQL request, it could look the following
UPDATE ... SET ..., version=version+1 WHERE version=10;
So, in case if record _was_ modified before, it will not be changed because of above mentione request. And you will be able to do some additional request to find that out and show message to user.
Many containers which supports managed-transactions also supports optimistic locking.
Hibernate supports optimistic locking, too.