I’ve read this tutorial: http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html but I think I’m still missing something.
Let us take an example:
- Thread T1 has its own Connection
- Thread T2 has its own Connection
So, these Threads perform a Transaction (setAutoCommit(false) on two different Connections). This Transaction executes, on a single DB Table, the following queries:
- Select a row to read a progressive number (PN)
- Insert a row setting the progressive number to: PN++ (what I’ve
read +1)
The Progressive Number must be unique (it is Primary Key) in this Table.
Do JDBC Transactions (with TRANSACTION_READ_COMMITTED isolation level) avoid the problem that T1 and T2 read the same value of PN and both try to insert in the table the same PN++? Is the Table locked until the Insert is performed and the commit() is called?
No, in order to make sure that you always have unique number you will need to:
1) [better] change the DB field to identity/sequence/auto-number depending on DB
2) use UUID as identifier
3) [worst] lock the row for the duration of read/increment/write sequence
TRANSACTION_READ_COMMITTED will only make sure that you can read ONLY the data that is already committed to DB. I.e. if you had another 200 DB operations between your
and
other threads would not be able to read the data that you updated until you commit, so in fact it will do quite the opposite of what you want.