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/02 Report--
This article introduces the relevant knowledge of "based on the transaction @ Transactional knowledge points in Spring". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
ACID, a set of operations within a transaction has atomicity, consistency, isolation, and persistence.
Atomicity (atomicity): all operations in a transaction are either completed or not completed, and do not end at some point in the middle. An error occurs during the execution of a transaction and is Rollback to the state it was in before the transaction started, as if the transaction had never been executed.
Consistency (consistency): the integrity of the database is not compromised before the transaction starts and after the transaction ends. This means that the data written must fully comply with all the preset rules, including the accuracy and concatenation of the data, and that the subsequent database can spontaneously complete the scheduled work.
Isolation (isolation): the ability of a database to allow multiple concurrent transactions to read, write and modify its data at the same time. Isolation can prevent data inconsistencies caused by cross execution when multiple transactions are executed concurrently. Transaction isolation is divided into different levels, including read uncommitted (Read uncommitted), read commit (read committed), repeatable read (repeatable read) and serialization (Serializable).
Durability (persistence): after the transaction is completed, the modification of the data is permanent, even if the system failure will not be lost.
Why use transactions?
In a set of operations, there are multiple update and modification operations, and in order to meet the relevant requirements of the transaction, transactions need to be used. The most common example is the transfer between two bank accounts, including A deduction, B to account and other operations, these operations need to have transaction characteristics. For example, either A successfully deducts money and B successfully arrives in the account; A deduction cannot occur and B does not receive the account (atomicity); now that AB is processed successfully, the money in An account increases again (persistence); nor can An account have sufficient initial balance and two concurrent processing, resulting in negative balance (isolation).
How do I use transactions?
Declarative annotated transactions can be used in spring, that is, on methods and classes that need to be used, use @ Transactional
Just embellish it. The decorated methods and classes are the wrapping areas of this transaction. A rollback is triggered in AOP when a corresponding exception occurs.
The default rollback is error and run exception, not including checking exception.
RollbackFor parameters can be set by users. For example, you can define exceptions and run exceptions, as shown below. Custom exception classes are also supported.
@ Transactional (rollbackFor = {Exception.class, RuntimeException.class})
The default transaction propagation mechanism is Propagation.REQUIRED
The essence of transaction propagation is to determine the restricted area of the transaction, that is, which code is protected by the transaction and can be rolled back if an exception occurs.
Minutiae:
If a transaction configuration exception occurs in the code, the exception within the transaction will be rolled back automatically; if the try catch is used in the corresponding method body to catch the exception and the exception is not thrown, it will not be rolled back and needs to be rolled back manually. Add the manual rollback TransactionAspectSupport.currentTransactionStatus (). SetRollbackOnly (); statement to the catch statement
The transaction of the public method takes effect.
Several results brought about by the propagation of transactions
If there is no transaction in the outer layer, there is no inner sub-method; if there is a transaction, there will be a transaction, and the effect of a transaction is like Propagation.REQUIRES_NEW, independent of each other, and each is a different new transaction.
If there is a transaction in the outer layer, then the whole method is within the scope of a transaction, and a rollback anywhere inside and outside is the whole rollback. But the Propagation.NESTED-decorated internal method, which can be rolled back separately, has the uniqueness of being an embedded child transaction.
With or without transactions on the outer layer, the methods modified by Propagation.REQUIRES_NEW are all independent transactions that independently control rollback and commit, and have nothing to do with outer transactions.
The transaction illustrated here refers to the propagation behavior with the default value of Propagation.REQUIRED, as well as the propagation behavior of Propagation.NESTED.
Two special cases
There are two methods An and B in the same class, and A calls the B method. A has no transaction, B has transaction, and rollback fails if there is an exception in B
A has no transaction A has no transaction B has no transaction the effect of no transaction does not analyze the transaction takes effect, the exception of B can make the whole A rollback B have transaction failure transaction to take effect, do not analyze as above
If A method B has a transaction and method B has no transaction in the same class, the transaction will take effect because the exception is passed to method A
Method A has no transaction, method B has transaction, and method A calls method B. Method B transactions are invalidated if Ahand B is in the same class. Method B has a transactional effect in different classes.
Cause analysis: this is caused by the dynamic proxy. When the rollback of the B method is to be performed, the B method called by A, which is not the class of the dynamic proxy, cannot be rolled back.
Method A calls method B cyclically, method A has transactions, method B enables new transactions, and method B successfully processes data submitted one by one; method B encounters an exception and rollback the one with exception, which does not affect the data that was successfully committed before.
Judging from the previous inference, the inner method modified by Propagation.REQUIRES_NEW is independent of a new transaction and has nothing to do with the outer layer. In fact, it is two transactions, and the outer transaction rollback memory will not be rolled back; the inner layer rollback does not affect the outer transaction.
However, the actual result is still a little different, if Amax B is in different classes, it can achieve this effect; if it is the same class, it will fail to roll back. The result is similar to the AB method call above.
The reason is that the dynamic proxy is used for transaction AOP, and the B method triggers the rollback is a transaction rollback exception. So to achieve the partial commit effect of calling between two methods in a class, you need to use the ApplicationContext context object to get the current class object, and then call the
/ / use the ApplicationContext context object to get the object; @ Autowiredprivate ApplicationContext applicationContext; CurrentClass classService = applicationContext.getBean (CurrentClass.class); / / then use this object to call other methods of the same kind, classService.b ()
Summary: the implementation of transactions depends on dynamic proxies, so when you use other methods of the class in the same class, you need to pay extra attention to the operation of transaction rollback only when the object of the dynamic proxy is used to call the method.
Transaction propagation property propagation
Propagation represents the propagation behavior of the transaction. The default value is Propagation.REQUIRED. The total attribute information is as follows:
Propagation.REQUIRED: join a transaction if it currently exists, and create a new transaction if it does not exist. (default propagation behavior, there must be a transaction)
(that is, if both method An and method B are annotated, in the default propagation mode, method A calls method B internally, merging the transactions of the two methods into one transaction.)
Propagation.SUPPORTS: join a transaction if it currently exists; if no transaction exists, continue to run in a non-transactional manner. (depending on whether there is a transaction at present, there can be a transaction or no transaction.)
Propagation.MANDATORY: join a transaction if it currently exists, or throw an exception if it does not exist. (requires that if there is a current transaction, it can be run; if not, it will be abnormal.)
Propagation.REQUIRES_NEW: recreate a new transaction and pause the current transaction if it exists.
(when the a method in class A uses the default Propagation.REQUIRED mode, the b method in class B plus the Propagation.REQUIRES_NEW mode, and then calls the b method in the a method to operate the database, however, after the a method throws an exception, the b method does not roll back because Propagation.REQUIRES_NEW suspends the transaction of the a method.)
Propagation.NOT_SUPPORTED: runs in a non-transactional manner, pausing the current transaction if there is a current transaction. (run in a non-transactional manner, currently there is no error report)
Propagation.NEVER: runs in a non-transactional manner, throwing an exception if a transaction currently exists.
Propagation.NESTED: if a transaction currently exists, it is executed within a nested transaction, and if there is no transaction, the effect is the same as Propagation.REQUIRED.
(that is, if both method An and method B add annotations, in A default propagation mode, method B plus Propagation.NESTED mode is used, method B is called inside method A, and method A rolls back, but method B rolls back, and method A does not roll back.)
Database isolation level
The isolation level of a transaction depends on the isolation level of the database. The default isolation level of mysql is repeatable read (repeatable read). The corresponding effect is to repeatedly read the data in a table within a transaction, which will always be the same, and will not read those modification records that have not been committed (dirty read) and committed (non-repeatable) by other transactions within this transaction scope.
When testing the isolation level of data, you need to make a series of settings for the database, including turning off autocommit and viewing the current isolation level, as shown in the following commands:
/ / because the variable autocommit divides the session system variable and the global system variable, the value of Value is ON, which means that autocommit is enabled. OFF indicates that autocommit is off. Show session variables like 'autocommit';show global variables like' autocommit'; / / turn off the autocommit set session autocommit=0; of the current session / / Open a transaction start transaction; begin; / / rollback rollback; / / commit transaction commot;// to view the current isolation level to view the global, the isolation level of the current session select @ @ tx_isolation;SELECT @ @ global.tx_isolation, @ @ session.tx_isolation / / set the isolation level of the current session to read uncommitted level: set session transaction isolation level read uncommitted; / / set the isolation level of the current session to read committed level: set session transaction isolation level read committed; / / set the isolation level of the current session to repeatable read level: set session transaction isolation level repeatable read; / / set the isolation level of the current session to serializable level: set session transaction isolation level serializable; / / Show connection idselect connection_id () / / Database timeout setting query show session variables like'% timeout'
The isolation levels of transactions are divided into uncommitted reads (read uncommitted), committed reads (read committed), repeatable reads (repeatable read), and serialization (serializable).
Each of these four categories will be explained below:
1. Unsubmitted reading (there will be dirty reading)
A transaction was executed but not committed; B transaction queried the updated data of A transaction; A transaction rolled back; then the previously read A transaction as committed data is dirty data. The lowest isolation level is rarely used.
-dirty reading, read unsubmitted data (add, modify and delete); in addition, there is the phenomenon of unrepeatable reading and phantom reading.
Transaction 1 is set as shown above, the isolation level is read uncommitted, and autocommit is turned off. At this point, you start a transaction and you see two pieces of data.
Open another window, turn off automatic submission, and then add and change.
As the final result is shown above, transaction 1 reads the data added, modified, and deleted when another transaction is not committed.
2. Submitted for reading
(there will be a phenomenon that can not be read repeatedly, because each read is the latest, so there may be a difference between the two times.)
It will read the change operations of other transactions on these data during this period of time, A transaction performs updates, B transaction queries, A transactions perform updates, and B transactions query again, the data queried before and after B transactions are inconsistent. For example, transaction B needs to update the status, so first make a query, the status is 1, after a series of operations, it will be updated immediately, at this time, query again, the status of the second query becomes 2.
-can not be repeated, generally refers to deletion, update, new; there will also be the phenomenon of phantom reading
The result of unrepeatable reading is that transaction 1 can read the addition, modification and deletion of other transactions, which is different from dirty reading in that one can only be read after committing, and the other can be read by uncommitted real-time operations.
3. Repeatable reading (operations that may overwrite other transactions)
Repeatable read is the default isolation level of mysql data, and it is also a widely used isolation level. The following focuses on its analysis.
No matter how many times A transaction is executed, as long as it is not committed, the query value of the same SQL in this transaction will never change; it can be understood that all queries in A transaction are data snapshots at the beginning of query A transaction.
Illusion: because of mutual isolation and repeatability, if another transaction is also processing the same data at the same time, there will be an illusory phenomenon, as if something is missing. For example, if both transactions take id to insert the same data, then the inserted data will fail to execute the lock (another transaction has not been committed) or the primary key conflicts (another transaction has been committed). If you query after the insertion failure, you will find that you have not found a repeat of that data, so you will have the feeling of reading blank and reading less content. Phantom reading is not only inserted, but also updated and deleted.
A realistic example is that before the bank repayment date, A went to check the bill table, obtained the bill data, obtained the sum, paid off the bill according to the bill synthesis, and inquired again, showing that it had been paid off. At this time, A submitted the query and repayment operation to the database, and before leaving work happily, he suddenly carried out the query bill operation again on a whim, suddenly there were several more consumption records, and he needed to repay the money again. A feels that the query before committing the transaction is a bit illusory, missing a few pieces of data.
Transaction 1 modifies and deletes the new operation to the same data after another transaction commits.
-Phantom reading, the general value is to add; that is, when you cannot query this data, you will report an error when you add it.
In fact, there will be updates and deletions, such as updating the same item with id+status, and later submitting will fail to update. This feature can also be used to lock the data, that is, CAS to update the data, so that the previous data will not be overwritten.
If the data that has been deleted is updated at this time, it will not take effect, and the data snapshot before deletion will be queried again in this transaction.
If only id is used to update the data, and there are concurrent modifications, then the later commit must override the update operation of the previous transaction. For example, the original data state is 1, transaction 2 will have the data state 1-> 2, while transaction 1 will see the same state as 1. If transaction 1 uses id to update directly, the data state will be changed to 3. Transaction 1 is thought to be 1-> 3, but it is actually 2-> 3, and the middle state 2 is overwritten directly. Therefore, highly concurrent updates need to be cautious.
Summary of phantom reading: many explanations for phantom reading are that while one transaction is querying, another transaction inserts data, and then the previous transaction will find several more pieces of data when it is queried again. This phenomenon does not exist. If it occurs, that means the current isolation level is that the read has been committed.
There is no doubt that what can be read repeatedly means that the data returned by multiple queries in the same transaction must be the same, which is the difference from reading committed. Therefore, it is only after the current transaction is committed that the query is refreshed to the change of another transaction.
Then the illusion that I understand is that after another transaction adds data and commits, the transaction at this time to add the same data will report an error, while at this time to query is to check no data, this phenomenon is illusory reading.
The update data level is that transaction 2 has committed the state change of the data, transaction 1 uses the old state as a condition to update, and the number of affected rows will be 0, which is also an illusion. Update the data that has been deleted, and the number of rows affected is 0.
The final execution of the database is serial, but some pre-operations can be concurrent, and finally updated to the database, there can only be a successful, due to some rules set, there will be the above phenomenon.
4. Serialization (no concurrent operations)
Serialization is the highest isolation level, that is, transactions are queued for serial execution, and the phenomena of dirty reading, non-repeatable reading and phantom reading mentioned above will not occur without concurrent operations. This is not often used and is easy to understand.
Summary: the isolation level of the database is what the effect will be on the concurrent operations of another transaction within one transaction.
Another transaction operation can see the modified data, that is, read the uncommitted
Another transaction operation that you can see after the transaction is submitted is to read the submitted data.
After another transaction operation is committed, the current transaction still does not see the corresponding modification. What data does the transaction begin and the same data is read at the end of the transaction, that is, it can be read repeatedly.
All transactions are queued up to be executed in turn, and only one can be modified at a time. Without parallelism, it is serialization.
The Spring transaction isolation level is one more default than the database transaction isolation level.
In addition to the above four isolation levels, there is an extra DEFAULT (default) this is a default isolation level for PlatfromTransactionManager, that is, the default transaction isolation level for the database. The other four correspond to the isolation level of JDBC, which can be explicitly specified.
The above is my personal experience. I hope I can give you a reference and I hope you can give me more support.
This is the end of the content of "what are the knowledge points of @ Transactional based on transactions in Spring". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.