In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "the detailed introduction of Spring transaction management". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the detailed introduction of Spring transaction management.
Review of the concept of transaction
What is a transaction?
A transaction is a logical set of operations, either executed or not performed.
Characteristics of things (ACID):
Atomicity: transactions are the smallest unit of execution and segmentation is not allowed. The atomicity of the transaction ensures that the action is either completed or does not work at all
Consistency: data is consistent before and after transaction execution
Isolation: when accessing the database concurrently, one user's things are not disturbed by other things, and the database is independent among the concurrent transactions.
Persistence: after a transaction is committed. Its changes to the data in the database are persistent, and even if the database fails, it should not have any impact on it.
Introduction of Spring transaction Management Interface
Spring transaction management interface:
PlatformTransactionManager: (platform) transaction manager
TransactionDefinition: transaction definition information (transaction isolation level, propagation behavior, timeout, read-only, rollback rules)
TransactionStatus: transaction running statu
The so-called transaction management is actually "commit or rollback operation according to the given transaction rules".
Introduction of PlatformTransactionManager Interface
Spring does not manage transactions directly, but provides a variety of transaction managers, which delegate the responsibility of transaction management to transactions of the relevant platform framework provided by persistence mechanisms such as Hibernate or JTA. The interface of Spring transaction manager is org.springframework.transaction.PlatformTransactionManager. Through this interface, Spring provides corresponding transaction managers for various platforms, such as JDBC, Hibernate, etc., but the specific implementation is the business of each platform.
The PlatformTransactionManager API code is as follows:
Three methods are defined in the PlatformTransactionManager interface:
Public interface PlatformTransactionManager (). {/ / Return a currently active transaction or create a new one, according to the specified propagation behavior (returns the currently active transaction or creates a new transaction, depending on the specified propagation behavior. ) TransactionStatus getTransaction (TransactionDefinition definition) throws TransactionException; / / Commit the given transaction, with regard to its status (commit the transaction using its current state) Void commit (TransactionStatus status) throws TransactionException; / / Perform a rollback of the given transaction (rollback the executed transaction) Void rollback (TransactionStatus status) throws TransactionException;}
We just talked about the interface implementation classes of PlatformTransactionManager in Spring according to different persistence layer frameworks. Several of the more common ones are shown in the following figure
For example, when we use JDBC or iBatis (that is, Mybatis) for data persistence operation, our xml configuration is usually as follows:
Introduction of TransactionDefinition Interface
The transaction manager interface PlatformTransactionManager obtains a transaction through the getTransaction (TransactionDefinition definition) method. The parameter in this method is the TransactionDefinition class, which defines some basic transaction properties.
So what are transaction attributes?
Transaction attributes can be understood as some basic configuration of the transaction, describing how the transaction strategy is applied to the method. The transaction attribute contains five aspects.
The methods in the TransactionDefinition interface are as follows:
The TransactionDefinition interface defines five methods and constants that represent transaction attributes such as isolation level, propagation behavior, and so on.
I only list the methods in the TransactionDefinition interface below and do not give the constants defined in the interface. The constant information in this interface will be described later.
Public interface TransactionDefinition {/ / returns the propagation behavior of the transaction int getPropagationBehavior (); / / returns the isolation level of the transaction, according to which the transaction manager controls which data within this transaction can be seen by another transaction int getIsolationLevel (); / returns the number of seconds in which the transaction must be completed / / returns the name of the transaction String getName (); int getTimeout (); / / returns whether the transaction is optimized to be read-only. Boolean isReadOnly ();}
(1) transaction isolation level (which defines the extent to which a transaction may be affected by other concurrent transactions):
Let's first look at the problems caused by concurrent transactions, and then introduce the five constants that represent the isolation level defined in the TransactionDefinition interface.
Problems caused by concurrent transactions
In a typical application, multiple transactions run concurrently, often manipulating the same data to complete their respective tasks (multiple users operate on unified data). Although concurrency is necessary, it can lead to the following problems.
Dirty read: when a transaction is accessing data and making changes to the data that have not yet been committed to the database, another transaction accesses the data and then uses the data. Because this data is data that has not yet been committed, then the data read by another transaction is "dirty data", and the operation based on "dirty data" may be incorrect.
Lost modification (Lost to modify): when one transaction reads data, another transaction also accesses the data, so after the data is modified in the first transaction, the second transaction also modifies the data. In this way, the result of the modification within the first transaction is lost, so it is called lost modification.
For example, transaction 1 reads the data in a table, transaction 2 also reads transaction 20, transaction 1 modifies A=A-1, transaction 2 also modifies A=A-1, and as a result, transaction 19, the modification of transaction 1 is lost.
Unrepeatable Unrepeatableread: refers to reading the same data multiple times within a transaction. Before this transaction ends, another transaction also accesses the data. Then, between the two reads in the first transaction, the data read by the first transaction may be different because of the modification of the second transaction. This occurs when the data read twice in a transaction is different, so it is called non-repeatable read.
Phantom read: phantom reading is similar to unrepeatable reading. It occurs when one transaction (T1) reads several rows of data, and then another concurrent transaction (T2) inserts some data. In the subsequent query, the first transaction (T1) will find some additional records that do not exist, as if there were hallucinations, so it is called phantom reading.
The difference between unrepeatability and illusion:
The focus of unrepeatable reading is modification, and the focus of phantom reading is to add or delete.
Example 1 (the same condition, you read the data, read it again and found that the value is not the same): before Mr. An in transaction 1 finished reading his salary of 1000, Mr. B in transaction 2 changed the salary of A to 2000. This leads A to change his salary to 2000 when he reads his salary again; this is non-repeatable.
Example 2 (under the same conditions, the number of records read out for the first time and the second time is not the same): if there are 4 people in a payroll table whose salary is greater than 3000, transaction 1 reads all the people whose salary is greater than 3000 and finds a total of 4 records. at this time, transaction 2 inserts a record with a salary greater than 3000, and when transaction 1 reads it again, the record becomes 5, which leads to illusion.
Isolation level
Five constants representing the isolation level are defined in the TransactionDefinition interface:
TransactionDefinition.ISOLATION_DEFAULT: use the default isolation level of the backend database, the default REPEATABLE_READ isolation level of Mysql, the default READ_COMMITTED isolation level of Oracle.
TransactionDefinition.ISOLATION_READ_UNCOMMITTED: the lowest isolation level that allows uncommitted data changes to be read, which may result in dirty, phantom, or unrepeatable reads
TransactionDefinition.ISOLATION_READ_COMMITTED: allows reading of committed data from concurrent transactions, prevents dirty reads, but phantom or unrepeatable reads can still occur
TransactionDefinition.ISOLATION_REPEATABLE_READ: the result of multiple reads to the same field is consistent, unless the data is modified by its own transaction, which can prevent dirty reading and unrepeatable reading, but phantom reading can still occur.
TransactionDefinition.ISOLATION_SERIALIZABLE: the highest isolation level, fully compliant with the isolation level of ACID. All transactions are executed one by one, so that interference between transactions is completely impossible, that is, this level prevents dirty reading, unrepeatable reading, and phantom reading. But this will seriously affect the performance of the program. This level is not usually used.
(2) transaction propagation behavior (in order to solve the transaction problem of calling each other between business layer methods):
When a transaction method is called by another transaction method, you must specify how the transaction should be propagated. For example, a method may continue to run in an existing transaction, or it may open a new transaction and run in its own transaction. The following constants that represent propagation behavior are included in the TransactionDefinition definition:
Support for the current transaction:
TransactionDefinition.PROPAGATION_REQUIRED: if there is a transaction, join it; if there is no transaction, create a new transaction.
TransactionDefinition.PROPAGATION_SUPPORTS: if there is a transaction, join it; if there is no transaction, continue to run in a non-transactional manner.
TransactionDefinition.PROPAGATION_MANDATORY: if there is a transaction, join it; if there is no transaction, throw an exception. (mandatory: mandatory)
The current transaction is not supported:
TransactionDefinition.PROPAGATION_REQUIRES_NEW: creates a new transaction and suspends the current transaction if it exists.
TransactionDefinition.PROPAGATION_NOT_SUPPORTED: runs in a non-transactional manner, suspending the current transaction if there is a current transaction.
TransactionDefinition.PROPAGATION_NEVER: runs in a non-transactional manner, throwing an exception if a transaction currently exists.
Other circumstances:
TransactionDefinition.PROPAGATION_NESTED: if there is a transaction, a transaction is created to run as a nested transaction of the current transaction; if there is no transaction, this value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED.
It is important to point out that the first six transaction propagation behaviors were introduced by Spring from EJB, and they share the same concept. And PROPAGATION_NESTED is unique to Spring. The transaction started with PROPAGATION_NESTED is embedded in the external transaction (if there is an external transaction). At this time, the embedded transaction is not an independent transaction, but depends on the existence of the external transaction. Only through the external transaction commit can it cause the commit of the internal transaction, and the nested sub-transaction can not be committed separately. If you are familiar with the concept of SavePoint in JDBC, it is easy to understand nested transactions. In fact, a nested subtransaction is an application of a SavePoint, and a transaction can include multiple Savepoints, each nested subtransaction. In addition, the rollback of external transactions can also lead to the rollback of nested subtransactions.
(3) transaction timeout attribute (the maximum time a transaction is allowed to execute)
The so-called transaction timeout refers to the maximum time a transaction is allowed to execute, and if the time limit is exceeded but the transaction has not been completed, the transaction is automatically rolled back. In TransactionDefinition, the timeout is represented by the value of int, in seconds.
(4) transaction read-only attribute (whether or not to perform read-only operations on thing resources)
The read-only attribute of a transaction refers to read-only or read-write operations on transactional resources. Transactional resources refer to those resources that are managed by transactions, such as data sources, JMS resources, custom transactional resources and so on. If we determine that only transactional resources are read-only, we can mark the transaction as read-only to improve the performance of the transaction. In TransactionDefinition, the boolean type is used to indicate whether the transaction is read-only.
(5) rollback rules (define transaction rollback rules)
These rules define which exceptions cause the transaction to roll back and which do not. By default, transactions are rolled back only if they encounter run-time exceptions, but not when they encounter check-type exceptions (this behavior is consistent with EJB's rollback behavior). But you can declare that the transaction rolls back as it encounters a run-time exception when it encounters a specific check-type exception. Similarly, you can declare that a transaction does not roll back when it encounters specific exceptions, even if those exceptions are run-time exceptions.
Introduction of TransactionStatus Interface
The TransactionStatus interface is used to record the state of a transaction. This interface defines a set of methods to obtain or judge the corresponding state information of the transaction.
PlatformTransactionManager.getTransaction (…) Method returns a TransactionStatus object. The returned TransactionStatus object may represent a new or existing transaction (if there is a qualified transaction in the current call stack).
The contents of the TransactionStatus API are as follows:
Public interface TransactionStatus {boolean isNewTransaction (); / / whether it is a new thing boolean hasSavepoint (); / / whether there is a recovery point void setRollbackOnly (); / / set to only roll back boolean isRollbackOnly (); / / whether to roll back only boolean isCompleted; / / whether completed} so far, I believe you have a deeper understanding of the "detailed introduction to Spring transaction management", you might as well do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.