I have a simple program that is modifying a database, which also may be run concurrently by different users.
In the program I have a few sequential operations reading/updating/inserting to the database that are dependent on each-other.
For example:
String selectQuery = "select order.[total] from order where id=?";
selectQuery.setString(1, "15679");
ResultSet queryResults = selectQuery.executeQuery();
if(queryResults.next() == false){
//execute insert into the order table
String insertQuery = "insert into order (id, total) values (?,?)";
.......
}
Now in the above example, there is no guarantee that two programs won't try to insert the order at the same time since they both may execute the select, get an empty result set, and then try to insert.
I understand in this example it is a little unrealistic since we could enforce uniqueness on the id
column which would stop duplicates from being inserted.
What I am trying to do is ensure that we can avoid this situation without locking the entire table? So we could guarantee that before the select query is executed that we can know that there will be no inserts/updates/reads on the row (which may or may not exist). After that we could release the lock on that row.