What is a Transaction (ACID)? What does setAutoCommit do?
A 43: A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other operations fail as well. For example if you transfer funds between two accounts there will be two operations in the set1. Withdraw money from one account.
2. Deposit money into other account.
These two operations should be completed as a single unit. Otherwise your money will get lost if the withdrawal is
successful and the deposit fails. There are four characteristics (ACID properties) for a Transaction.
Atomicity :
All the individual
operations should
either complete or fail.
Consistency:
The design of the
transaction should
update the database
correctly.
Isolation :
Prevents data being corrupted by concurrent
access by two different sources. It keeps
transactions isolated or separated from each
other until they are finished.
Ensures that the database
is definitely updated once
the Transaction is
completed.
Durability:
Transactions maintain data integrity. A transaction has a beginning and an end like everything else in life. The
setAutocommit(….), commit() and rollback() are used for marking the transactions (known as transaction
demarcation). When a connection is created, it is in auto-commit mode. This means that each individual SQL
statement is treated as a transaction and will be automatically committed immediately after it is executed. The way
to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:
try{
Connection myConnection = dataSource.getConnection();
// set autoCommit to false
myConnection .setAutoCommit(false);
withdrawMoneyFromFirstAccount(.............); //operation 1
depositMoneyIntoSecondAccount(.............); //operation 2
myConnection .commit();
}
catch(Exception sqle){
try{
myConnection .rollback();
}catch( Exception e){}
}
finally{
try{if( conn != null) {conn.close();}} catch( Exception e) {}
}
The above code ensures that both operation 1 and operation 2 succeed or fail as an atomic unit and consequently
leaves the database in a consistent state. Also turning auto-commit off will provide better performance.