How to operate transactions in SpringBoot?
There are two ways to operate transactions in Spring Boot: programmatic transactions or declarative transactions. Next, let's take a look at the specific implementation of the two.
1. Programmatic Transactions
There are two more ways to implement programmatic transactions in Spring Boot:
Implement programmatic transactions using TransactionTemplate objects;
Programmatic transactions are implemented using the lower-level TransactionManager object.
Their specific implementation codes are as follows.
1.1 TransactionTemplate usage
To use the TransactionTemplate object, you need to inject the TransactionTemplate into the current class first, and then use the execute method provided by it to execute the transaction and return the corresponding execution result. If an exception occurs during the execution of the program, you can use the code to manually roll back the transaction. The specific implementation code is as follows:
1.2 TransactionManager usage
It is relatively troublesome for TransactionManager to implement programmatic transactions. It needs to use two objects: a subclass of TransactionManager, plus TransactionDefinition transaction definition object, then obtain and open the transaction by calling getTransaction of TransactionManager, and then call the commit method provided by TransactionManager to submit the transaction, or Another method, rollback, is used to roll back a transaction. Its specific implementation code is as follows:
As can be seen from the above code , it is more flexible to use a programmatic transaction, but the writing method is more troublesome .
2. Declarative Transactions
The implementation of declarative transactions is relatively simple. You only need to add the @Transactional annotation to the method or class. When the @Transactional annotation is added, the transaction can be automatically opened before the method is executed; the transaction is automatically committed after the method is successfully executed. ; If an exception occurs during the execution of the method, it will automatically roll back the transaction.
Its specific use is as follows:
Of course, @Transactional supports the setting of many parameters, and its parameter setting list is as follows:
The parameter setting method is as follows:
In this article we have introduced two ways of implementing transactions: programmatic transactions or declarative transactions. Among them, the programmatic transaction is divided into two implementations: using the TransactionTemplate object or the lower-level TransactionManager object to implement the programmatic transaction respectively, their advantages are higher flexibility, and transactions can be added to any code fragment; while the implementation of declarative transactions Even simpler, just add the @Transactional annotation to the class or method to automatically open and commit (and rollback) transactions.