Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Detailed explanation of java transaction

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "detailed explanation of java affairs". In daily operation, I believe many people have doubts about the detailed explanation of java affairs. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "detailed explanation of java affairs"! Next, please follow the editor to study!

Transaction concept

We need to understand the concept of transaction: what is a transaction? A transaction is a concurrency control unit and a user-defined sequence of operations. There are four features (ACID):

Atomicity: a transaction is the logical working unit of a database, and all the operations included in the transaction are either done or not done.

Consistency: the result of transaction execution must be to change the database from one consistency state to another. Consistency is closely related to atomicity.

Isolation: the execution of one transaction cannot be interfered with by other transactions.

Persistence / Durability: once a transaction is committed, its changes to the data in the database should be permanent.

The above is a written explanation, to put it simply, to unify your operations, either all operations are successful or unsuccessful, if one of the operations fails, all previous operations are rolled back to the state before the series of operations were performed.

Dirty, unrepeatable, phantom reading

It is much easier to understand these three kinds of data reading problems caused by concurrent access before understanding the transaction isolation level.

Dirty reading

A transaction reads data that has not been committed by B transaction, and if B transaction has an error and performs a rollback operation, then the data read by A transaction is dirty data. It is as if the original data is clean and pure, and at this time the data is no longer pure because the B transaction has changed it. At this time, transaction An immediately reads the dirty data, but transaction B finds conscience and uses rollback to restore the data to its original clean and pure appearance, while transaction A knows nothing. The final result is that transaction A reads the dirty data this time, which is called dirty reading.

This often happens in money transfer and withdrawal operations.

Can not be read repeatedly (read many times before and after, the data content is inconsistent)

Transaction An is performing a read operation, and the whole transaction An is relatively large, so it takes a long time to read the same data before and after. However, when transaction A reads the data for the first time, for example, the age of Xiaoming is 20 years old, transaction B performs a change operation to change Xiaoming's age to 30 years old, and when transaction A reads Xiaoming's age for the second time, it is found that its age is 30 years old, which is different from the previous data, that is, the data is not duplicated, and the system cannot read the repeated data and become non-repeatable.

Phantom reading (read many times before and after, the total amount of data is inconsistent)

Transaction A needs to count the total amount of data twice when performing the read operation. After the previous query on the total amount of data, transaction B performs the operation of adding new data and commits it. At this time, the total amount of data read by transaction An is different from the previous statistics. Just like an illusion, there are several more pieces of data for no reason, which becomes an illusion.

Summary: what's the difference between unrepeatable reading and fantasy reading?

(1) non-repeatable read means reading data changed by other transactions, aiming at update operation.

Solution: use a row-level lock to lock the row, and transaction A does not release the lock until multiple read operations have been completed, allowing other transactions to change the data just now.

(2) Phantom reading reads new data from other transactions, aiming at insert and delete operations.

Solution: use a table-level lock to lock the entire table, and transaction A reads the total amount of data several times before releasing the lock, which allows other transactions to add data.

At this point, it is much easier to understand the transaction isolation level.

Isolation level of database transaction

The four isolation levels defined by the SQL standard are adopted by ANSI (American National Standards Institute) and ISO/IEC (International Standard). Each level has a different impact on the processing power of transactions. A transaction is a series of actions that together make a complete unit of work, which must be completed, and if one fails, the transaction rolls back to its original state as if nothing had happened.

There are four isolation levels for database transactions, which are Read uncommitted, Read committed, Repeatable read and Serializable from low to high. These four levels can solve the problems of dirty reading, unrepeatable reading and phantom reading one by one.

DEFAULT

The default value, which indicates that the default isolation level of the underlying database is used. Most databases are READ_COMMITTED (MySql default REPEATABLE_READ)

READ UNCOMMITTED (read unsubmitted)

This isolation level means that one transaction can read data modified by another transaction that has not yet been committed. This level does not prevent dirty and unrepeatable reads, so the isolation level is rarely used.

READ_COMMITTED (read submit)

This isolation level means that one transaction can only read data that has been committed by another transaction. This level prevents dirty reading, which is the recommended value in most cases.

REPEATABLE_READ (repeatable)

This isolation level means that a transaction can execute a query repeatedly throughout the process, and the records returned each time are the same. Even if there is new data that satisfies the query between multiple queries, these new records are ignored. This level prevents dirty reading and non-repeatable reading.

SERIALIZABLE (serialization)

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. Under this isolation level, all transactions are executed sequentially, and the InnoDB engine of MySQL database implicitly adds a read sharing lock to read operations, thus avoiding dirty reads, unrepeatable readings and phantom reads.

MVCC (multi-version concurrency control)

In mysql, the default transaction isolation level is repeatable read (repeatable-read). In order to solve the problem of non-repeatable read, innodb uses MVCC (multi-version concurrency control) to solve this problem. MVCC takes advantage of adding two hidden columns (create version number and delete version number) after each piece of data, and each transaction starts with an incremental version number, which is used to compare with the version number of each row of records queried. MYSQL MVCC

Spring transaction propagation behavior

Let's first introduce the use of Spring transaction propagation behavior:

@ Transactional (propagation=Propagation.REQUIRED) public void test () {/ / todo something}

Annotate @ Transactional by using the propagation property setting, for example: @ Transactional (propagation = Propagation.REQUIRED)

Its propagation attribute has the following values:

Public enum Propagation {REQUIRED (TransactionDefinition.PROPAGATION_REQUIRED), SUPPORTS (TransactionDefinition.PROPAGATION_SUPPORTS), MANDATORY (TransactionDefinition.PROPAGATION_MANDATORY), REQUIRES_NEW (TransactionDefinition.PROPAGATION_REQUIRES_NEW), NOT_SUPPORTED (TransactionDefinition.PROPAGATION_NOT_SUPPORTED), NEVER (TransactionDefinition.PROPAGATION_NEVER), NESTED (TransactionDefinition.PROPAGATION_NESTED);}

Transaction propagation behavior:

REQUIRED: if there is a transaction, join it; if there is no transaction, create a new transaction.

SUPPORTS: if there is a transaction, join it; if there is no transaction, continue to run in a non-transactional manner.

MANDATORY: if there is a transaction, join it; if there is no transaction, throw an exception.

REQUIRES_NEW: creates a new transaction and suspends the current transaction if it exists.

NOT_SUPPORTED: runs in a non-transactional manner, suspending the current transaction if there is a current transaction.

NEVER: runs in a non-transactional manner, throwing an exception if a transaction currently exists.

NESTED: if there is a transaction, create a transaction to run as a nested transaction of the current transaction; if there is no transaction, this value is equivalent to REQUIRED

Two implementations of Spring transaction

Spring supports programmatic transaction management and declarative transaction management:

Programmatic transactions: programmatic transactions use TransactionTemplate or directly use the underlying PlatformTransactionManager to implement transactions. For programmatic transactions Spring, it is recommended to use TransactionTemplate to manage transactions.

2 declarative transactions: declarative transactions are based on AOP. Its essence is to intercept the method before and after, then create or join a transaction before the target method starts, and then "commit" or "roll back" the transaction according to the execution of the target method.

The difference between two kinds of transaction management

Programmatic transactions allow users to precisely define the boundaries of transactions in code.

Declarative transactions help users decouple operations from transaction rules, which are implemented by Spring containers based on AOP, and developers only focus on business logic implementation.

Programmatic transactions invade the business code, but provide finer transaction management. The declarative transaction is based on AOP, so it not only plays the role of transaction, but also does not affect the specific implementation of the business code. Declarative transactions are generally recommended, especially the @ Transactional annotation, which can help developers implement transactions, reduce the amount of code development, and make the code look cleaner and tidy.

Spring programmatic transaction

Generally speaking, there are two ways to implement programmatic transactions: template transaction (TransactionTemplate) and platform transaction manager (PlatformTransactionManager).

Template transaction method (TransactionTemplate): mainly uses TransactionTemplate class to implement transactions, which is also a programming method recommended by Spring officially.

Example:

① gets template object TransactionTemplate

② selects the transaction result type

③ business data operation processing

④ business execution completes transaction commit or rollback when an exception occurs

The execute of TransactionTemplate can accept two types of parameters to execute transactions, which are:

TransactionCallback (): executes a transaction and can return a value. TransactionCallbackWithoutResult (): no value is returned when the transaction is executed.

Here is an example of using TransactionTemplate:

@ Servicepublic class TransactionExample {/ * * 1, get TransactionTemplate object * * / @ Autowired private TransactionTemplate transactionTemplate Public void addUser () {/ / 2, use TransactionCallback or TransactionCallbackWithoutResult to execute transaction transactionTemplate.execute (new TransactionCallbackWithoutResult () {@ Override public void doInTransactionWithoutResult (TransactionStatus transactionStatus) {try {/ / 3), execute business code (here simulation, execute multiple database operation methods) userMapper.delete (1) UserMapper.delete (2);} catch (Exception e) {/ / 4. Rollback transactionStatus.setRollbackOnly ();}} if an exception occurs

Platform transaction manager mode (PlatformTransactionManager): here, the most basic transaction management bureau is used to manage transactions, and with the help of PlatformTransactionManager and TransactionDefinition and TransactionStatus core classes of Spring transactions, transactions are operated.

Use the transaction manager to implement the transaction steps:

① gets transaction manager PlatformTransactionManager

② gets transaction attribute definition object TransactionDefinition

③ gets the transaction status object TransactionStatus

④ business data operation processing

⑤ performs transaction commit commit operation or transaction rollback rollback operation when an exception occurs

@ Servicepublic class TransactionExample {/ * * 1, get PlatformTransactionManager object * * / @ Autowired private PlatformTransactionManager platformTransactionManager; public void addUser () {/ / 2, get default transaction definition DefaultTransactionDefinition def = new DefaultTransactionDefinition (); / / set transaction propagation behavior def.setPropagationBehavior (TransactionDefinition.PROPAGATION_REQUIRED) / / 3. According to the properties set by the transaction definition object, get the transaction status TransactionStatus status = platformTransactionManager.getTransaction (def); try {/ / 4, execute the business code (here for simulation, perform multiple database operation methods) userMapper.delete (1); userMapper.delete (2) / / 5. Transaction commit platformTransactionManager.commit (status);} catch (Exception e) {/ / 5; transaction rollback platformTransactionManager.rollback (status);} Spring declarative transaction

A declarative transaction (declarative transaction management), as its name implies, uses a declarative approach to handle transactions. This method is based on Spring AOP, which decouples the specific business logic and transaction processing. Its essence is to intercept before and after the execution of the method, create or join a transaction before the method starts, and commit or roll back the transaction according to the execution situation after the execution of the target method.

Commonly used methods for declarative transactions

Common ways to use declarative transactions are

1 XML

2 @ Transactional Annotation

The two methods, due to the popularity of SpringBoot in recent years, provide very convenient automatic configuration, resulting in the gradual elimination of XML, and the use of annotations is recommended.

The scope of @ Transactional

The annotation @ Transactional can be added not only to the method, but also to the class level. When the note is liberated at the class level, it means that all public methods of that class are configured with the same transaction attribute information. If @ transactional is configured at the class level and @ transactional is configured at the method level, the application manages the transaction with method-level transaction attribute information, in other words, the method-level transaction attribute information overrides the relevant configuration at the class level.

Configurable parameters in @ Transactional annotation

Value: transaction manager, this configuration item sets the Bean name in the Spring container, and this Bean needs to implement the interface PlatformTransactionManager.

TransactionManager: transaction manager, this parameter is consistent with the value configuration and is the same thing.

Isolation: transaction isolation level, default is Isolation.DEFAULT level

Propagation: transaction propagation behavior, default is Propagation.REQUIRED

Timeout: the transaction timeout (in seconds). The default value is-1. When the transaction times out, an exception is thrown and the rollback operation is performed.

ReadOnly: whether to enable read-only transactions and read-only transactions. Default is false.

RollbackForClassName: the exception class name definition of the rollback transaction, which is the same as rollbackFor, but with the class name.

NoRollbackForClassName: specify which exception names do not roll back the transaction. The parameter is a class array, which is the same as noRollbackFor, but is defined by the name of the class.

RollbackFor: rollback the transaction exception class definition. When an exception occurs in the method and the exception class is the same as the class specified by this parameter, the rollback operation is performed, otherwise the transaction is committed.

NoRollbackFor: specifies which exceptions occur and does not roll back the transaction. When an exception occurs in the method and the exception class is the same as the class specified by this parameter, the transaction will continue to be committed instead of rolling back.

Example @ Transactional (propagation=Propagation.REQUIRED) public void test () {/ / todo something}

Note: in general, it is not recommended to configure @ Transaction on a class, as this is likely to force later maintainers to use transactions.

Points to pay attention to when using transactions

1. If an exception is detected, it will not be rolled back. The reason: it is only rolled back at the default RuntimeException level. If it is an exception at the Eexception level, it needs to be added manually.

@ Transactional (rollbackFor=Exception.class)

2. Things do not take effect after catching an exception. The reason: the catch handles the exception so that the framework cannot perceive the exception, so it cannot be rolled back. Suggestion: if it is not the actual business requirement, the exception is thrown uniformly in the business layer, and then handled uniformly in the control layer.

@ Transactional (rollbackFor=Exception.class) public void test () {try {/ / Business Code} catch (Exception e) {/ / TODO: handle exception} / / actively catching exceptions makes the framework unable to catch exceptions, thus causing things to fail} so far, the study on "detailed explanation of java transactions" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report