Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a transaction in JDBC?

Connection.setTransactionIsolation(int) warns:

Note: If this method is called during a transaction, the result is implementation-defined.

This bring up the question: how do you begin a transaction in JDBC? It's clear how to end a transaction, but not how to begin it.

If a Connection starts inside in a transaction, how are we supposed to invoke Connection.setTransactionIsolation(int) outside of a transaction to avoid implementation-specific behavior?

like image 538
Gili Avatar asked Feb 09 '11 02:02

Gili


2 Answers

Answering my own question:

  • JDBC connections start out with auto-commit mode enabled, where each SQL statement is implicitly demarcated with a transaction.
  • Users who wish to execute multiple statements per transaction must turn auto-commit off.
  • Changing the auto-commit mode triggers a commit of the current transaction (if one is active).
  • Connection.setTransactionIsolation() may be invoked anytime if auto-commit is enabled.
  • If auto-commit is disabled, Connection.setTransactionIsolation() may only be invoked before or after a transaction. Invoking it in the middle of a transaction leads to undefined behavior.

See JDBC Tutorial by Oracle.

like image 108
Gili Avatar answered Oct 12 '22 21:10

Gili


JDBC implicitly demarcates each query/update you perform on the connection with a transaction. You can customize this behavior by calling setAutoCommit(false) to turn off the auto-commit mode and call the commit()/rollback() to indicate the end of a transaction. Pesudo code

try {   con.setAutoCommit(false);     //1 or more queries or updates     con.commit(); } catch(Exception e) {    con.rollback(); } finally {    con.close(); } 

Now, there is a type in the method you have shown. It should be setTransactionIsolation(int level) and is not the api for transaction demarcation. It manages how/when the changes made by one operation become visible to other concurrent operations, the "I" in ACID (http://en.wikipedia.org/wiki/Isolation_(database_systems))

like image 24
Aravind Yarram Avatar answered Oct 12 '22 21:10

Aravind Yarram