Question

I need to explicitly lock a row in table for a Connection, which:

  • reads in data;
  • (some logic will be run in between)
  • updates the corresponding row in the db;

While other connections wouldn't be able to read the data, disabling the dirty read (so ISOLATION level is out of question).

Read the documentation, but don't fully comprehend it. Is my current understanding correct:

  • set the concurrency control model to MVCC;
  • set the transaction isolation level to READ COMMITTED (already default actually);
  • set the autocommit value to false for Connection object in hand;
  • create Statement/PreparedStatement;
  • run the 'SELECT /--/ FOR UPDATE' query on the statement or PreparedStatement object and receive the ResultSet;
  • -execute some logic-
  • update the row with either ResultSet updateX() method or new UPDATE sql (executeUpdate()).
  • commit the changes.

Are any steps superfluous, missing or have I completely misunderstood the whole concept?

Was it helpful?

Solution

The correct way to do this is to update the row at the beginning and at the end. The steps from creating the statement are below.

  • create Statement
  • update the row with its existing values (or the changed values if it is known at this point)
  • perform other operations
  • update the row with changed values (if not done before)
  • commit

If you don't do it like the above, another transaction could change the row before this transaction can change it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top