Basic knowledge of database transactions

Although Spring provides a flexible and convenient transaction management features, but these features are based on the underlying transaction mechanism of the database itself work. To learn more about Spring's transaction management and configuration, it is necessary to the basics of database transactions learning.


1. What is a database transaction
"a prosperity, a loss for both sides." "This sentence is thought to reflect the transaction, a lot of complicated things to be step by step, but they make up a whole, either as a whole to take effect, or overall failure. This kind of thinking reflected in the database, that is, multiple SQL statements, or perform all succeed or all fail.

Database transaction strictly defined, it must satisfy four properties: atomicity (Atomic), consistency (Consistency), isolation (Isolation) and persistence (Durabiliy), referred to as ACID. The following is a description of each feature.

1) atom of: represents a transaction consisting of a plurality of database operations are indivisible atomic units, only if all operations performed, and the entire transaction submission. Any database operation failed transaction, any operation has been performed must be withdrawn, so that the database is returned to the initial state.

2) Consistency: After a successful transaction operations, in which the state of the database and its business rules are the same, that data will not be destroyed. Such as transfer money from account A to account B 100 yuan, regardless of the success of the operation, total deposits accounts A and B accounts is unchanged.

3) Isolation: The concurrent operation of data, the transaction has a different respective data space, they do not interfere with the operation of the other. Rather, the requirements do not completely interference-free. Provides a variety of database transaction isolation level, different isolation levels correspond to the degree of interference, the higher the isolation level, data consistency is better, but the weaker concurrency.

4) Durability: Once a transaction is committed successfully, the transaction data in all operations must be persisted to the database. Even after the transaction is committed, the database immediately crashes, restart the database, it must ensure that data can be recovered through some mechanism.

In these transactions characteristics, the data "consistency" is the ultimate goal, other features are measures to achieve this goal to take, requirements or means.

A database management system commonly used to ensure the re-execution log atomicity, consistency and durability. Heavy execution log records every movement database changes, database error occurred after the exit part of the implementation of operations in a transaction, you can undo the database has been performed under the Heavily execution log. Further, for the transaction have been presented, even if the database crashes, when restarting the database can be re-perform the corresponding operations on persistent data has not been based on the log.

And Java programs using object-locking mechanism similar thread synchronization, database management system using a database lock isolation mechanisms to ensure the transaction. When multiple transactions are trying to operate on the same data, transaction data only to operate the lock is held until after the previous transaction is completed, the subsequent transactions have a chance to operate on the data. Oracle Database also uses data version of the mechanism, the rollback data for each change will save a version of the changes to the data without affecting the data is read.


2. The data concurrency issues

A database may have multiple access clients, these clients are available for concurrent access to the database.

The same data in the database may be accessed simultaneously by multiple affairs, if not taken the necessary quarantine measures will lead to all kinds of concurrency problems, undermine the integrity of the data. These problems can be attributed to five categories, including three types of data read problem (dirty read, non-repeatable read and phantom read) and Class 2 data update problems (first type and second type of lost updates lost updates). The following are examples to explain the scene by causing the problem.

1) dirty read (dirty read)
to change the data B is read transaction A transaction has not been committed, and operate on the basis of this data. If you happen to B transaction is rolled back, then A transaction read data is simply not recognized. Raised when concurrent transactions and transfers of view teller transaction dirty reads scene.

In this scenario, B hope withdrawals $ 500, but later withdrew the motion, while the A to the same account transfer $ 100, because A transaction reads data B transaction has not submitted, resulting in the loss of 500 yuan in vain account . In the Oracle database, the case of dirty read does not occur.

2) Non-repeatable read (unrepeatable read)

A non-repeatable read transaction reads means B to change the data transaction has committed. A withdrawal is assumed that during the transaction, B is the account transfer to 100 yuan, A balance of the account two reads inconsistencies occur.

In the same transaction, the account deposit balance point in time T4 and T7 time to read inconsistent.

3) Phantom read (phantom read)

A transaction reads new transaction data submitted by B, then A phantom read affairs issues will appear. Phantom read generally occurs in the calculation of the statistical data transaction. For example, assume that the total amount of the banking system twice in the same transaction deposit accounts statistics, statistical process twice, just added a savings account and deposit $ 100, then the total statistics twice amount will be inconsistent.

If the new data just to meet the affairs of the query, then the new data is entered the field of vision of the transaction, resulting in inconsistent statistics two cases.

Phantom reads and non-repeatable read is easy to confuse the two concepts, the former refers to read other new data has been submitted to the transaction, while the latter refers to the read transaction has been submitted to change the data (change or delete). To avoid either case, take countermeasures is different: to prevent changes to the data read, data is added only to the operation of row-level locking to prevent data operations changes; and avoid reading the new data, it often needs adding table lock one hundred and eleven will lock the entire table to prevent new data (Oracle data using multiple versions of manner).

4) The first category is missing update

When A transaction retraction, the update data B transaction has been submitted covers. This error can cause very serious problems, it can be seen from the following account withdrawals transfers.

A transaction at the time of the revocation, "accidentally" B transaction will amount has been transferred to the account wiped out.

5) The second category is missing update

A transaction data covering B transaction has committed, resulting in the loss of B firm to do the operation.

In the above example, because the check transfer transaction covers transactions made to update withdrawal of deposits, the bank finally lead to a loss of $ 100. On the contrary, if the first transfer transaction commits, the user account will lose 100 yuan.

 

3. Database lock mechanism

Data concurrency can cause a lot of problems, and in some cases some of the problems are allowed, but in other cases can be fatal. Database lock mechanism to solve the problem by concurrent access, although there are differences in different databases on the implementation details, but the principle is basically the same.

按锁定的对象的不同,一般可以分为表锁定和行锁定。前者对整张表进行锁定,而后者对表中的特定行进行锁定。从并发事务锁定的关系上看,可以分为共享锁定和独占锁定。共享锁定会防止独占锁定,但允许其他的共享锁定。而独占锁定既防止其他的独占锁定,也防止其他的共享锁定。为了更改数据,数据库必须在进行更改的行上施加行独占锁定,INSERT、UPDATE、DELETE 和 SELECT FOR UPDATE 语句都会隐式采用必要的行锁定。下面介绍一下Oracle数据库常用的5种锁定。

1)行共享锁定:一般通过 SELECT FOR UPDATE 语句隐式获得行共享锁定,在Oracle中用户也可以通过 LOCK TABLE ROW SHARE MODE 语句显式获得行共享锁定。行共享锁定并不防止对数据行进行更改操作,但是可以防止其他会话获取独占性数据表锁定。允许进行多个并发的行共享和行独占锁定,还允许进行数据表的共享或者采用共享行独占锁定。

2)行独占锁定:通过一条 INSERT、UPDATE 或 DELETE 语句隐式获取,或者通过一条 LOCK TABLE IN ROW  EXCLUSIVE MODE语句显式获取。这种锁定可以防止其他会话获取一个共享锁定、共享行独占锁定或独占锁定。

3)表共享锁定:通过 LOCK TABLE IN SHARE MODE 语句显式获得。这种锁定可以防止其他会话获取行独占锁定(INSERT、UPDATE 或 DELETE),或者防止其他表共享行独占锁定或表独占锁定,但它允许在表中拥有多个行共享和表共享锁定。该锁定可以让会话具有对表事务级一致性访问,因为其他会话在用户提交或者回滚该事务并释放对该表的锁定之前不能更改这张被锁定的表。

4)表共享行独占锁定:通过 LOCK TABLE IN SHARE ROW EXCLUSIVE MODE 语句显式获得。这种锁定可以防止其他会话获取一个表共享、行独占或者表独占锁定,但允许其他行共享锁定。这种锁定类似于表共享锁定,只是一次只能对一张表放置一个表共享行独占锁定。如果A会话拥有该锁定,则B会话可以执行 SELECT FOR UPDATE操作;但如果B会话试图更新选择的行,则需要等待。

5)表独占锁定:通过 LOCK TABLE IN EXCLUSIVE MODE 语句显式获得。这种锁定可以防止其他会话对该表的任何其他锁定。

 

4.事务隔离级别

尽管数据库为用户提供了锁的DML操作方式,但直接使用锁管理是非常麻烦的,因此数据库为用户提供了自动锁机制。只要用户指定会话的事务隔离级别,数据库就会分析事务中的SQL语句,然后自动为事务操作的数据资源添加适合的锁。此外,数据库还会维护这些锁,当一个资源上的锁数目太多时,自动进行锁升级以提高系统的运行性能,而这一过程对用户来说完全是透明的。

ANSI/ISO SQL 92 标准定义了4个等级的事务隔离级别,在相同的数据环境下,使用相同的输入,执行相同的工作,根据不同的隔离级别,可能导致不同的结果。不同的事务隔离级别能够解决的数据并发问题的能力是不同的,如下表所示:

事务的隔离级别和数据库并发性是对立的。一般来说,使用 READ UNCOMMITED 隔离级别的数据库拥有最高的并发性和吞吐量,而使用 SERIALIZABLE 隔离级别的数据库并发性最低。

SQL 92 定义 READ UNCOMMITED 主要是为了提供非阻塞读的能力。Oracle 虽然也支持  READ  UNCOMMITED,但它不支持脏读;因为 Oracle 使用多版本机制彻底解决了在非阻塞读时读到脏数据的问题并保证读的一致性,所以,Oracle 的 READ COMMITTED 隔离级别就已经满足了 SQL 92 标准的 REPEATABLE READ 隔离级别。

SQL 92 推荐使用 REPEATABLE READ 以保证数据的读一致性,不过用户可以根据应用的需要选择适合的隔离等级。

 

5.JDBC对事务的支持

并不是所有的数据库都支持事务,即使支持事务的数据库也并非支持所有的事务隔离级别。用户可以通过 Connection#getMetaData() 方法获取 DatabaseMetaData 对象,并通过该对象的 supportsTransactions()、supportsTransactionIsoationLevel(int level) 方法查看底层数据库的事务支持情况。

Connection 默认情况下是自动提交的,即每条执行的 SQL 语句都对应一个事务。为了将多条SQL语句当成一个事务执行,必须先通过 Connection#setAutoCommit(false) 阻止 Connection 自动提交,并通过 Connection#setTransactionIsolation() 设置事务的隔离级别。Connection 中定义了对应 SQL 92 标准4个事务隔离级别的常量。通过 Connection#commit() 提交事务,通过 Connection#rollback() 回滚事务。下面是典型的 JDBC事务数据操作的代码,如下图所示。

在 JDBC 2.0 中,事务最终只能有两个操作:提交和回滚。但是,有些应用可能需要对事务进行更多的控制,而不是简单地提交或回滚。JDBC 3.0(Java1.4及以后的版本)引入了一个全新的保存点特性,Savepoint 接口允许用户将事务分割为多个阶段,用户可以指定回滚到事务的特定保存点,而并非像 JDBC 2.0 一样只能回滚到开始事务的点,如下图所示。

下面的代码使用了保存点功能,在发生特定问题时,回滚到指定的保存点,而非回滚整个事务,如下图所示。

并非所有数据库都支持保存点功能,用户可以通过 DatabaseMetaData#supportsSavepoints() 方法查看是否支持。

Guess you like

Origin www.cnblogs.com/jwen1994/p/11291827.html