Spring isolation levels and propagation behavior
Isolation level
1, dirty reads: refers to a transaction to be able to read another uncommitted transaction data 2:3, repeatable read, read and write, can solve the problem of dirty reading, reading and writing to submit, after reading data, add a user to delete, add data, read data will change (produce phantom read) 4, serialization: solve the phantom reads the questionCopy the code
Propagation behavior
Propagation behavior refers to the invocation problem between methods. In most cases, we think of things as all or nothing at once. For example, if the business is successful, but the finance is not up to standard and is rejected by the finance department, then all transactions need to be rolled back. However, there will also be special scenarios, such as credit card repayment, for repayment processing, but we find that one of the cards is abnormal, then we can not roll back all the executed credit card data, but only the abnormal card. Rolling back all credit cards that have been paid means that people who paid on time are also considered delinquent, which is obviously not reasonable. In other words, when we do each card operation, we want to have an independent transaction to control it, so that each card repayment does not interfere with each other.
mode of transmission | meaning | note |
---|---|---|
PROPAGATION_REQUIRED | If a transaction exists, the current transaction is supported. Enable if there are no transactions | This is Spring’s default propagation behavior |
PROPAGATION_SUPPORTS | If a transaction exists, the current transaction is supported. If there is no transaction, the execution is non-transactional | – |
PROPAGATION_MANDATORY | If one already exists, the current transaction is supported. If there is no active transaction, an exception is thrown | – |
PROPAGATION_REQUIRES_NEW | Always start a new transaction. If a transaction already exists, suspend the existing transaction | In the credit card scenario, we often need this propagation behavior to create a separate transaction for each card |
PROPAGATION_NOT_SUPPORTS | Always execute nontransactionally and suspend any existing transactions | – |
PROPAGATION_NEVER | Always execute nontransactionally, throwing an exception if there is an active transaction | – |
PROPAGATION_NESTED | Run in a nested transaction if an active transaction exists; If there are no active transactions, follow the TransactionDefinition. The PROPAGATION_REQUIRED attribute executes | – |
The code example
@Service
public class RoleServiceImpl {
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public int insertRoleList(List<Role> roles){
for(Role role : roles){
this.isnertRole(role);//insretRole annotations are invalid}}}Copy the code
The resources
Mybatis technology principle and actual combat