How do I lock database records from Java?
Solution 1
In case of MySQL, you can use, SELECT FOR UPDATE
statement for locking the records. Lock will not be released until the transaction completes or rolls back.
More on the same here.
Solution 2
It depends on the environment you are working on. for a container managed transaction your container manages the transactions for you and all you have to do is to set the Lockmode to lockmode.write. What this does is that it blocks all write access to the class methods while userA is accessing record 1. On the other hand for a stand alone application you can just add Synchronization key word to your method to control concurrent access. I hope this helps.
Comments
-
Mahesh almost 2 years
I'm developing a database program in Java with dbf. I need to know how to lock the database records from the Java side.
Example: we have a database table
cheques
with 5 records in the table (record 1
through5
). There are 2 users,user-1
anduser-2
.user-1
accessesrecord 1
anduser-2
tries to accessrecord 1
at the same time. I want to lockrecord 1
to prevent access to that record byuser-2
whileuser-1
is accessing it. How do I do this in Java?