This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
preface
A transaction is one or more database operations that require simultaneous atomicity, isolation, consistency, and persistence
This article will explain the two implementations of springBoot transactions, programmatic and declarative, before covering the basics: the four characteristics of a transaction, the isolation level of a transaction, and the propagation behavior of a transaction
Four Characteristics of transactions (ACID)
- Atomicity: All operations in a transaction are indivisible in the database and either all or none of them are executed.
- Consistency: Several transactions executed in parallel, the results of which must be consistent with those executed sequentially in a certain order.
- Isolation: Transactions execute without interference from other transactions, and the intermediate results of transaction execution must be transparent to other transactions.
- Durability: For any committed transaction, the system must guarantee that the transaction’s changes to the database are not lost.
Open the transaction
@EnableTransactionManagement
Copy the code
SpringBoot declarative transactions
Transactional Transactional can be used on classes or public methods. If used on a class, the transaction is enabled on all public methods, and the transaction on the method takes effect if it exists on both classes and methods
Can be used on a class
@Transactional(rollbackFor=Exception.class)
public class TransactionServiceImpl implements TransactionService {
}
Copy the code
It’s more methodological use
@Override
@Transactional(rollbackFor=Exception.class)
public void t1(Student one) {
}
Copy the code
@Transactional
The parameters of the
attribute | role |
---|---|
value | You can use this property to specify which transaction manager to select when multiple transaction managers are configured. |
transactionManager | You can use this property to specify which transaction manager to select when multiple transaction managers are configured. |
propagation | Propagation behavior of transactions. The default value is Propagation.REQUIRED |
isolation | The Isolation level of the transaction, which defaults to Isolation.default |
timeout | The timeout period for a transaction. The default value is -1. If the timeout limit is exceeded but the transaction has not completed, the transaction is automatically rolled back. |
readOnly | Specifies whether the transaction is read-only. The default value is false. To ignore methods that do not require a transaction, such as reading data, you can setread-only To true. |
rollbackFor | Used to specify the type of exception that can trigger transaction rollback. Multiple exception types can be specified. |
rollbackForClassName | Used to specify the type of exception that can trigger transaction rollback. Multiple exception types can be specified. |
noRollbackFor | Throws the specified exception type, without rolling back the transaction, or you can specify multiple exception types. |
noRollbackForClassName | Throws the specified exception type, without rolling back the transaction, or you can specify multiple exception types. |
Value is the same as transactionManager rollbackFor is the same as rollbackForClassName noRollbackFor is the same as noRollbackForClassName
Isolation level of transactions (Isolation)
Transaction isolation level | Dirty read | Unrepeatable read | Phantom read |
---|---|---|---|
Read uncommitted (read-uncommitted) | is | is | is |
Read -committed | no | is | is |
Repeatable read | no | no | is |
Serializable | no | no | no |
Propagation of transactions
Propagation behavior | explain |
---|---|
REQUIRED | If a transaction currently exists, join the transaction, if not, create a new transaction. |
SUPPORTS | If a transaction exists, join the transaction. If no transaction currently exists, it continues in a non-transactional manner. |
MANDATORY | If a transaction exists, join the transaction. If no transaction currently exists, an exception is thrown. |
REQUIRES_NEW | Re-create a new transaction and suspend the current transaction if one exists. |
NOT_SUPPORTED | Runs in a non-transactional manner, suspending the current transaction if one exists. |
NEVER | Runs in a non-transactional manner, throwing an exception if a transaction currently exists. |
NESTED | The same effect as REQUIRED. |
SpringBoot programmatic transactions
This approach is based on AOP functionality, so it needs to be added
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Copy the code
Write the configuration class
@aspect @configuration public class MyTransactionConfig {/** * Config method expiration time, Default -1, never timeout */ private final static int tx_time_out = 10; Private static Final String POITCUT_EXPRESSION = "execution(*) zdc.enterprise.service.impl.*.*(..) ) "; @Autowired private PlatformTransactionManager platformTransactionManager; @ Bean public TransactionInterceptor txadvice () {/ * read-only things, do not update delete * / / * * / transaction management rules RuleBasedTransactionAttribute readOnlyRule = new RuleBasedTransactionAttribute(); /* Sets whether the current transaction is a read-only transaction, true: readonlyrule-setreadOnly (true); /* TransactionDefinition defines the transaction isolation level; * If a transaction exists, join the transaction; If there is no transaction currently, it continues in a non-transactional manner. */ readOnlyRule.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); / * increased transaction rules * / deletion RuleBasedTransactionAttribute requireRule = new RuleBasedTransactionAttribute (); / * throw an exception executed after cutting rolled back Suggest custom exception * / requireRule. SetRollbackRules (Collections. SingletonList (new RollbackRuleAttribute(Exception.class))); /*PROPAGATION_REQUIRED: The transaction isolation is 1, and if a transaction exists, join it. If there is no transaction currently, a new transaction is created. This is the default value. */ requireRule.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); /* Set transaction invalidation time beyond 10 seconds */ requireRule. SetTimeout (TX_METHOD_TIME_OUT); NameMap declares the name of the method that needs to manage the transaction. SetNameMap */ Map<String, TransactionAttribute> nameMap = new HashMap<>(); nameMap.put("add*", requireRule); nameMap.put("save*", requireRule); nameMap.put("insert*", requireRule); nameMap.put("update*", requireRule); nameMap.put("delete*", requireRule); nameMap.put("remove*", requireRule); /* Namemap. put(" Batch *", requireRule); nameMap.put("get*", readOnlyRule); nameMap.put("query*", readOnlyRule); nameMap.put("find*", readOnlyRule); nameMap.put("select*", readOnlyRule); nameMap.put("count*", readOnlyRule); NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource(); source.setNameMap(nameMap); TransactionInterceptor transactionInterceptor = new TransactionInterceptor(platformTransactionManager, source); return transactionInterceptor; } / * * * Settings section = tangent point pointcut + notice TxAdvice * @ return * / @ Bean public Advisor txAdviceAdvisor () {AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(POITCUT_EXPRESSION); return new DefaultPointcutAdvisor(pointcut, txadvice()); }}Copy the code
With this Transactional class configured, do not use @Transactional on your class or on every method that matches the method name prefix. RuleBasedTransactionAttribute parameters and the parameters of the @ Transactional roughly the same, there are detailed annotations, but more explanation
Source: author: ZOUZDC links: https://juejin.cn/post/7028963866063306760 re the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code