Transaction: a bunch of operation in logic, the unit which consists the operation will works all or breaks down all.
Every operation of MySQL server is a independent transaction in default situation.
TPL(Transaction Processing Language):
start transaction
commit
rollback
SQL statement:
CREATE TABLE account( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40), money FLOAT ); INSERT INTO account(name,money) VALUES('aa',1000); INSERT INTO account(name,money) VALUES('aa',1000); INSERT INTO account(name,money) VALUES('aa',1000); START TRANSACTION; UPDATE account SET money=money-100 WHERE name='aa'; UPDATE account SET money=money+100 WHERE name='bb'; COMMIT;
JDBC code:
package com.pp.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import org.junit.Test; import com.pp.util.JdbcUtil; public class TransactionDemo { @Test public void test1() { Connection connection = null; PreparedStatement pstatement = null; try { connection = JdbcUtil.getConnection(); // start transaction connection.setAutoCommit(false);
// set the isolation level
connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
pstatement = connection .prepareStatement("UPDATE accout SET money=money-100 WHERE name='aa'"); pstatement.executeUpdate(); pstatement = connection .prepareStatement("UPDATE accout SET money=money-100 WHERE name='aa'"); pstatement.executeUpdate(); // commit connection.commit(); } catch (Exception e) { e.printStackTrace(); } finally { } } }
The feature of Transaction:
1. Atomicity: the statement in one transaction can not be seperated.
2. Consistency: the transaction should keep the data in database from one status to another consistent status, for example: transfer money.
3. Isolation: the transaction should not be disturbed or broke down when multi-thread prolems occurs.
4. Durability: the submited data should be stored in durability, for example: in the disk.
Transaction isolation:
1. If ignore the transaction isolation, will lead to the following problems:
a. Dirty read: one transaction reads the other transaction's unsubmited data
b. Non-repeatable read: one transaction reads the other transaction's submited data
c. Phantom read: one transaction reads the the other transaction's insert data
2. How to controll the isolation level?
READ UNCOMMITTED: a,b,c are possible
READ COMMITTED: prevent a but b,c are possible
REPEATABLE READ: prevent a and b, but c are possible
SERIALIZEBLE: prevent a,b and c
MySQL's default isolation level is REPEATABLE READ
Oracle's default isolation level is READ COMMIETTED
Check current MySQL data base isolation level:
SELECT @@tx_isolation;
Set the current transaction's isolation level:
SET TRANSACTION ISOLATION LEVEL isolation_level_name;(must set before the current transaction starts)
Update lost:
One transaction override the other transaction's submitted data