SpringBoot (eighteen) transactions

Table of contents

spring transaction

1. Introduction to Spring affairs

1. Transaction isolation level

2. Transaction propagation behavior

3. Declarative transaction attributes

4. Transaction rollback rules

5. Precautions for using @Transactional

2. Encoding implementation


spring transaction

1. Introduction to Spring affairs

Spring transactions can not only use transaction annotation @Transactional, but also support programmatic use of transactions, but this mode is not commonly used. Spring transactions are described in detail here.

1. Transaction isolation level

In fact, only one annotation @Transactional is used to use transactions, which is Spring's annotation transactions. The transaction isolation level refers to the degree of isolation when several transactions are concurrent. Spring declares that transactions can set Spring's transaction isolation level through the isolation attribute. Which provides the following five transaction isolation levels. @Transactional(isolation=IsolationDEFAULT): The default transaction isolation level, that is, the transaction isolation level of the database.

The database has the following four isolation levels:

1. Read uncommitted Under this level, when a transaction is modifying a row of data, another transaction is not allowed to modify the row of data, but another transaction is allowed to read the row of data. Therefore, at this level, there will be no update loss, but dirty reads and non-repeatable reads will occur.

2. Read committed At this level, uncommitted write transactions do not allow other transactions to access the row, so dirty reads will not occur; but transactions that read data allow other transactions to access the row data, so there will be The case of non-repeatable read.

3. Repeatable read Under this level, read transactions prohibit write transactions, but allow read transactions, so there will be no situation where the same transaction reads different data twice (non-repeatable read), and write transactions prohibit everything else affairs.

4. Serializable This level of serialization requires that all transactions must be executed serially, so it can avoid all problems caused by concurrency, but the efficiency is very low.

The higher the isolation level from top to bottom, the better the integrity and consistency of data can be guaranteed, but the greater the impact on concurrency performance, the lower the security. The lower the isolation level, the higher the security . For most applications, it is preferable to set the isolation level of the database system to ReadCommitted. It can avoid dirty reads and has better concurrency performance. Although it can cause concurrency issues such as non-repeatable reads, phantom reads, and lost updates of the second type, in individual occasions where such problems may occur, the application can use pessimistic or optimistic locking to control them.

2. Transaction propagation behavior

Transaction propagation behavior refers to the behavior that Spring will handle these transactions if multiple transactions exist at the same time. The transaction propagation behavior is divided into the following types.

It can be seen that 1, 2, and 3 form a group, all of which show support for the current transaction. The most important thing is the current transaction processing method. Then 7 alone in a group.

For example, if there is method A in a service, method B is called, and the propagation behavior of method B is PROPAGATION_REQUIRED, then if the propagation behavior of method A is also PROPAGATION_REQUIRED, when method A runs, a transaction is started, method A When method B is executed in the middle, it is aware that there is already a transaction, method B will not create a new transaction, and it will be directly included in the transaction of method A.

1. PROPAGATION REQUIRED: If there is a current transaction, join the transaction; if there is no current transaction, create a new transaction, which is Spring's default transaction propagation behavior. 2. PROPAGATION REOUIRES NEW: Create a new transaction, if there is a current transaction, suspend the current transaction. The new transaction has nothing to do with the suspended transaction, they are two independent transactions. When the rollback of the outer transaction fails, the execution result of the inner transaction cannot be rolled back, and the inner and outer transactions cannot interfere with each other. 3. PROPAGATION SUPPORTS: If there is a transaction currently, join the transaction; if there is no transaction, continue to run in a non-transactional manner. 4. PROPAGATION NOT SUPPORTED: Run in a non-transactional mode. If there is a current transaction, suspend the current transaction. 5. PROPAGATION NEVER: Run in a non-transactional mode. If there is a current transaction, an exception will be thrown. 6. PROPAGATION MANDATORY: If there is a current transaction, join the transaction; if there is no current transaction, throw an exception. 7. PROPAGATIONNESTED: If there is a current transaction, create a transaction to run as a nested transaction of the current transaction; if there is no current transaction, the value is equivalent to PROPAGATIONREQUIRED

3. Declarative transaction attributes

Spring transactions not only have transaction isolation level and transaction propagation behavior, but also contain many attributes for developers to use, which are described below.

ovalue: store the value of String type, which is mainly used to specify different transaction managers, satisfying that there are different transaction managers in the same system. For example, multiple transaction managers are declared in the Spring container, and then developers can specify the transaction manager to be used according to the settings. Usually, in a scenario where a system needs to access multiple databases, multiple transaction managers are set up, and then different choices are made.

transactionManager: Similar to value, it is also used to select a transaction manager. propagation: transaction propagation behavior, the default value is PropagationREQUIRED. isolation: the isolation level of the transaction, the default value is IsolationDEFAULT timeout: the timeout period of the transaction, the default value is -1, if the execution is not completed after the set time, the current transaction will be automatically rolled back. readOnly: Whether the current transaction is a read-only transaction, the default value is false. Usually you can set the attribute value of the transaction that reads data to true. rollbackFor: You can set the specified exception that triggers the transaction, allowing multiple types of exceptions to be specified. noRollbackFor: Contrary to rollbackFor, you can set specified exceptions that do not trigger transactions, allowing multiple types of exceptions to be specified.

4. Transaction rollback rules

Spring's transaction rollback is usually when an exception is thrown based on the current transaction, the Spring transaction manager catches the unhandled exception, and then decides whether the current transaction is rolled back according to the rules. If the caught exception happens to be an exception that sets the notRollbackFor attribute, it will not be caught. In the default configuration, Spring will only rollback when it catches a subclass of RuntimeException (RuntimeException).

5. Precautions for using @Transactional

When using the @Transactional annotation, you need to pay attention to some situations:

@Transactional needs to be used above the class, not above the interface. If it is used on the interface, the transaction will be invalid. @Transactional can only be used on public modified methods. If it is used on private or protected modified methods, the transaction will be invalid. @Transactional Try not to use it above the class, because it will use transactions for all methods in the class. If you use transactions for query methods, it may affect efficiency.

2. Encoding implementation

mapper interface

@Mapper //该注解就可以不用在配置类中扫描mapper接口包了
public interface UserMapper{
​
    void insertUser1();
​
    void insertUser2();
​
}

mapper mapping file

<mapper namespace="com.yka.mapper.UserMapper">
    <insert id="insertUser1">
        insert into t_user(name)value ('杨凯奥1')
    </insert>
​
    <insert id="insertUser2">
        insert into t_user(name)value ('杨凯奥2')
    </insert>
</mapper>

service layer

public interface UserService {
    void insertUser1();
​
    void insertUser2();
}
@Service
public class UserServiceImpl implements UserService {
​
    @Autowired
    private UserMapper userManager;
​
    @Override
    public void insertUser1() {
        userManager.insertUser1();
    }
​
    @Override
    public void insertUser2() {
        userManager.insertUser2();
    }
​
​
}

controller

@Controller
public class TransactionalController {
​
    @Autowired
    private UserService userService;
​
    @RequestMapping("/Transactional")
    @Transactional//添加事务注解
    public void test(){
        userService.insertUser1();
        System.out.println(1/0);//除0异常
        userService.insertUser2();
    }
​
}

After running, there was a division by 0 exception, so it was rolled back, and the two SQL statements were not added to the database

If you do not add the transaction sql1 can be added successfully, but sql2 cannot be added successfully

Guess you like

Origin blog.csdn.net/m0_65992672/article/details/130451288