Series Catalogue
A brief discussion on Spring affairs (I.) business
Spring Transaction Details (ii) source code detailed
Spring Transaction Details (iii) test validation
Spring Transaction Details (IV.) Summary improvement
Introduction
Many coder use database transactions when they do not understand the principles of the transaction, even the basic concepts, and are extremely prone to error and write code that they cannot control. Many articles on the Internet are either concepts, or a bit of source code, or a little test validation, are not enough to fully understand the transaction, so this article appears, this series of spring transactions contains four parts:
The first chapter is about concept, which has an understanding of the whole of affairs.
The second chapter from the source to see the underlying implementation mechanism.
The third chapter tests the validation of the example.
The fourth chapter summarizes the improvement.
This preparation, expect to learn together, personal ability is limited, there is any improper, trouble points out.
The full text is based on the MySQL InnoDB engine. MySQL Official documents: Airline tickets, recommended books:MySQL technology insider-INNODB storage engine.
I. BACKGROUND
Spring business leader called Juergen Hoeller, Jürgen ... He wrote almost all of the spring transaction code. Read the source first worship God, master his style of source code, read it will be much smoother.
Transactions (Transaction) are one of the important features of a database that differs from a file system. The current internationally recognised database design principle is the acid feature, which guarantees the correct execution of database transactions. The transaction in MySQL's InnoDB engine is fully acid-compliant.
Second, the acid characteristics of the transaction
(After the arrow, translated from the official website: InnoDB and the ACID Model)
atomicity (atomicity): A transaction must be considered an indivisible minimum unit of work, and all operations in the entire transaction either commit successfully or all fail back. --" mainly related to InnoDB affairs. related features: Transaction Commit, rollback, information table.
Consistency (consistency): The database is always transitioning from one consistent state to another . The integrity constraints of the database were not compromised before and after the transaction started. For example, if uniqueness is violated, the transaction must be revoked and the initial state returned. --" primarily involves internal innodb processing to protect data from crashes, related features: double write buffering, crash recovery.
Isolation (Isolation): The objects of each read and write transaction can be separated from each other transaction's operands, that is, the transaction is not visible to other transactions before committing , usually internal lock implementation. --" The main concerns are transactions, especially the transaction isolation level, related features: Isolation level, the underlying implementation details of the InnoDB lock.
persistence (Durability): Once a transaction commits, its modifications are persisted to the database. -- The interaction between MySQL software features and specific hardware configurations, related features: 4 configuration items: Double write buffer switch, level of transaction commit flush log, Binlog synchronization frequency, table file, write cache, operating system for fsync()的支持、
backup policy, etc.
Third, the properties of the transaction
To guarantee the ACID properties of a transaction, spring defines 6 properties for the transaction, corresponding to the declarative transaction annotations (org.springframework.transaction.annotation.Transactional) @ Transactional (key1=*,key2=* ...)
- transaction name : The user can manually specify the name of the transaction, When you have multiple transactions, you can distinguish which transaction is used. The attribute in the corresponding annotation is value, TransactionManager
- Isolation Level : in order to solve the problem that the database is prone to, the classification locks up the processing policy. The properties in the corresponding annotation isolation
- Time-out : defines how long a transaction execution is timed out so that it can be rolled back after a time-out. You can prevent long-running transactions from consuming resources. property in the corresponding annotation timeout
- read-only : This transaction reads only the data but does not update the data, which helps the database engine to tune the transaction. Properties in corresponding annotations readonly
- propagation mechanism : defines the propagation characteristics of a transaction in a total of 7 types. Properties in the corresponding annotation propagation
- rollback mechanism : Defines a rollback policy when an exception is encountered. Properties in the corresponding annotations rollbackfor, norollbackfor, Rollbackforclassname, Norollbackforclassname
The isolation level and the propagation mechanism is more complex, we carefully product a product.
3.1 Isolation Level
This piece is more complex, we see from 3 points of view:3 kinds of error phenomena, MySQL's underlying technical support, hierarchical processing strategy . This section must be good-looking and has begun to involve the core principles.
1. phenomenon (three types of problems)
Dirty Read (drity Read): Transaction A updated record but not committed, transaction B queries out a uncommitted record.
non-repeatable read (Non-repeatable Read): transaction A reads once, at which point the transaction B updates or deletes the data, and transaction a again queries for inconsistent data.
Phantom Reading (Phantom Read): Transaction A reads once, at which point the transaction B inserts a data transaction a again query, more records.
2. MySQL's underlying support( consistent non-lock readVS Lock Read)
- Consistent non-locking read (MySQL implicit processing)
Consistent non-lock read (consistent nonlocking read) refers to the InnoDB storage engine using multiple versioning (multi versionning) to read data from a row in the current execution time database. If the read row is performing a delete or update operation, this is the release of the read operation that will not wait for the row to be locked. Instead, InnoDB will read a snapshot of the row data
The above shows the non-locking read of InnoDB storage engine conformance. It is called non-locking read because there is no need to wait for the release of the X lock on the accessed row. Snapshot data refers to the data in the previous version of the row, which is done through the undo segment. While undo is used to rollback data in a transaction, the snapshot data itself has no additional overhead, and the read snapshot data does not need to be locked because no transaction requires modification of the historical data. In MVCC, the read operation can be divided into two categories, snapshot read (Snapshot read) and current read.
Snapshot Read : normal Select
Current Read :
- SELECT * FROM table where? lock in Share mode; (Plus s lock)
- SELECT * FROM table where? for update; (plus x Lock)
- Insert, UPDATE, delete operation is preceded by the current read (plus x Lock)
- Lock read (user explicitly use)
InnoDB supports two locking reads for the SELECT statement ( Intent lock intention Locks):
1) SELECT ... For UPDATE: Adds an exclusive lock (x Lock) to the row being read, and other transactions cannot add any locks to the locked row.
2) SELECT ... Lock in SHARE MODE: Add a shared lock (s lock) to the read row, and the other transaction can add S lock, and the X lock will block the wait.
Note: Both types of locks must be in a transaction, transaction commit, lock release. So must begin or start transaction open a transaction or simply set autocommit=0 turn autocommit off (mysql default is 1, that is, execute SQL commit immediately)
3. Tiered processing strategy (four isolation levels)
Website Description:
INNODB supports each transaction isolation level with a different locking policy. You can use strong consistency (the default repeatable Read) for operations on critical data (acid compliance). For data operations that are not so important, you can use Read committed/read uncommitted. Serializable performs more stringent rules than can be reread for special scenarios: Troubleshooting XA transactions, concurrency, and deadlock issues.
Four levels of isolation:
1.Read Uncommitted(reads uncommitted content): May read uncommitted data from other transactions. (Dirty Read + non-repeatable READ + Phantom Read)
2.Read Committed (read submissions) : A transaction can only see changes that have been submitted to the firm. (at the RC isolation level, a consistent, non-locked read data snapshot is the latest version .) However, other transactions may have new commits, so the same select may return different results. (Non-REPEATABLE READ + Phantom Read)
3.Repeatable Read(can be reread):
1. Enable repeatable reads: Multiple consistent non-locking reads within the same transaction, the RR takes thesnapshot version that was created the first time it was read, guaranteeing repeatable reads within the same transaction, which is also the default isolation level for InnoDB.
2. solve the Phantom reading problem and use lock to solve . Lock read (for update or lock in SHARE MODE), UPDATE, and DELETE, lock one row or multiple rows, as follows:
1) for a unique index with unique search criteria, InnoDB only locks the index records found.
2) For other search conditions, InnoDB locks the scanned index range, uses Next-key locks, and blocks the insert operation of the other session to the gap. Therefore , the user must use lock read to solve the Phantom reading problem under RR isolation LEVEL!!! .
4.Serializable (serializable) : This is the highest isolation level, which is to add a shared lock (lock in SHARE MODE) to each read row of data. At this level, a large number of timeouts and lock competitions can be caused, primarily for distributed transactions .
As the following table:
Mysql-innodb Possible problem statistics
Different isolation levels/issues that may arise |
Dirty Read |
Non-REPEATABLE READ |
Phantom reading |
Read Uncommitted (Read UNCOMMITTED content) |
|
|
|
Read Committed (read submissions) |
|
|
|
Repeatable Read (can be reread) |
|
|
|
Serializable (Serializable) |
|
|
|
The above table needs to pay special attention to the RR level under the MySQL InnoDB or phantom read phenomenon, just need users must use lock read to solve the Phantom reading problem!
3.2 Propagation mechanisms
Org.springframework.transaction package has a transaction definition interface Transactiondefinition, defines 7 kinds of transaction propagation mechanism, many people's misunderstanding of the propagation mechanism starts from the concept, so specially translated the source code comment as follows:
1.propagation_required
Support the current transaction, or, if it does not exist, create a new one. An EJB transaction property similar to the same name. This is typically the default setting for a transaction definition and typically defines the transaction synchronization scope.
2.propagation_supports
Supports the current transaction and, if there is no transaction, executes it in a non-transactional manner. An EJB transaction property similar to the same name.
Attention:
For transaction managers with transactional synchronization, Propagation_supports is slightly different from no transaction because it may define synchronization within the scope of a transaction. Therefore, the same resources (JDBC connection, hibernate sessions, and so on) will be shared throughout the specified range . Note that the exact behavior depends on the actual synchronization configuration of the transaction manager!
Careful use of propagation_supports! in particular, do not rely on propagation_required or propagation_requires_new, within the Propagation_supports range ( This can cause synchronization conflicts at runtime). If this nesting is unavoidable, ensure that the transaction manager is configured appropriately (typically switching to "synchronization on actual transactions").
3.propagation_mandatory
Supports the current transaction, or throws an exception if the current transaction does not exist. An EJB transaction property similar to the same name.
Attention:
Transaction synchronization within the Propagation_mandatory range is always driven by the surrounding transaction.
4.propagation_requires_new
Creates a new transaction, suspending the current transaction if there is a current transaction. An EJB transaction property similar to the same name.
Note: Actual transaction hangs will not be available out of the box on all transaction managers. This is especially true for Jtatransactionmanager, which requires transactionmanager support.
The propagation_requires_new scope always defines its own transactional synchronization. Existing synchronizations will be suspended and restored appropriately.
5.propagation_not_supported
The current transaction is not supported and is always performed in a non-transactional manner. An EJB transaction property similar to the same name.
Note: Actual transaction hangs will not be available out of the box on all transaction managers. This is especially true for Jtatransactionmanager, which requires transactionmanager support.
Transaction synchronization is not available within the propagation_not_supported range. Existing synchronizations will be suspended and restored appropriately.
6.propagation_never
The current transaction is not supported and an exception is thrown if the current transaction exists. An EJB transaction property similar to the same name.
Note: transaction synchronization is not available in the Propagation_never range .
7.propagation_nested
If the current transaction exists, it is executed in the nested transaction, if there is no transaction, similar to propagation_required. There are no similar features in EJBS.
Note: The actual creation of nested transactions is only valid for a specific transaction manager. Out of the box, this applies only to the Datasourcetransactionmanager (JDBC 3.0 driver). Some JTA providers may also support nested transactions.
Iv. Summary
This section explains the 4 major features of transactions and the concept of 6 large attributes. and a simple extension of the concept. Perhaps we will be more ignorant force ha, do not worry only need to have a concept in mind, the next chapter we from the bottom source to see the implementation mechanism of the transaction.
======= Reference ========
MySQL Official documents: Airline tickets
Book: "MySQL Technology insider-innodb Storage Engine"