How to encode optimistic and pessimistic locking from java code

I know what an optimistic and pessimistic lock is, but when you write Java code, how do you do it? Suppose I use Oracle with Java, do I have any methods in JDBC to help me do this? How can I customize this thing? Any pointers would be appreciated.

+6
source share
2 answers

This way you can implement optimistic locks in your DB table (this is how optimized locking is done in Hibernate):

  • Add an integer column "version" to your table.
  • Increase the value of this column each time the corresponding row is updated.
  • To get the lock, just read the version value of the string.
  • Add the condition "version = received_version", where the condition is your update statement. Check the number of rows affected after the update. If the lines are not affected, someone has already changed your entry.

Your update should look like

UPDATE mytable SET name = 'Andy', version = 3 WHERE id = 1 and version = 2 

Of course, this mechanism only works if all parties follow it, unlike gateways that do not require special processing.

Hope this helps.

+11
source

Suppose I use Oracle with Java, do I have any methods in JDBC to help me do this?

This Oracle document should provide you with some tips on how to do this.

There are no specific JDBC methods. Rather, you achieve optimistic locking, as you design your SQL queries / updates and place transaction boundaries.

+3
source

All Articles