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?


Solution 1:

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.

Solution 2:

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))

Solution 3:

I suggest you read this you'll see

Therefore, the first call of setAutoCommit(false) and each call of commit() implicitly mark the start of a transaction. Transactions can be undone before they are committed by calling

Edit:

Check the official documentation on JDBC Transactions

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. (To be more precise, the default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)

The way to allow two or more statements to be grouped into a transaction is to disable the auto-commit mode. This is demonstrated in the following code, where con is an active connection:

con.setAutoCommit(false);

Source: JDBC Transactions