Record locking

April 22nd, 2003

Matt Raible asks how to lock a DB record in a webapp. A method that always works (I learnt it from a VB guru (yes, those do exist)), is a very bare-bones optimistic locking. On each table, add a column LAST_EDITED, of date type. Now, whenever you do an update, include the LAST_EDITED in your WHERE clause, and fill in the local time. So you get:

UPDATE my_table SET blah='bluh', LAST_EDITED=now WHERE blah='bleh' AND LAST_EDITED=time-you-got-from-your-select-query
IIRC, the "now" is a function in Oracle. The alternative is to provide another time (System.getTimeInMillis()), but this will only work for 99.99% of the cases (granted, if you happen to have 2 updates on the same split millisecond (according to 2 different machines), you'll probably get gray hair trying to solve it anyways).

As always, I'm not sure if I made myself clear. Drop a comment if I didn't.

Leave a Reply