SpringBoot transaction annotation @Transactional

SpringBoot provides very convenient transaction operations. You can implement transaction rollback through annotations, which is very convenient and fast. Let's talk about how to perform transaction operations.

1. Business description

In Spring, there are two ways to implement transactions, which are programmatic transaction management and declarative transaction management. 
Programmatic transaction management: Programmatic transaction management uses TransactionTemplate or directly uses the underlying PlatformTransactionManager. For programmatic transaction management, Spring recommends using TransactionTemplate. 
Declarative transaction management: Built on top of AOP. Its essence is to intercept before and after the method, and then create or add a transaction before the target method starts, and submit or roll back the transaction according to the execution after the target method is executed. 
Declarative transaction management does not require intrusion code, and transaction operations can be performed through @Transactional, which is faster and simpler. Recommended Use

2. How to use

Using transactions in Mybatis is very simple. You only need to add the annotation @Transactional to the function without any configuration. Let's take a look at the example of adding transactions in the controller layer:

@Autowired
OrderServiceorderService;   //order操作的Service层

@ApiOperation(value = "增加OrderCustomer")
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
@Transactional
public JsonBean<Order> insertOrder(@RequestParam(value = "order") String order) {
    try {
        //创建订单
        Order order = orderService.insert(user.getId(),is_company,fk_want_company_id);
        return new JsonBean(SUCCESS, orderCustomer);
    } 
    catch (ErrorCodeException e)
    {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return new JsonBean(e.getErrorCode());
    }
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==


@Transactional can act on interfaces, interface methods, classes, and class methods. When used as a class, all public methods of the class will have the transaction attribute of this type. At the same time, we can also use this annotation at the method level to override the class-level definition. Therefore, it can be used in the Service layer and the Controller layer. The above example is implemented in the Controller layer. We simulate an order submission interface, where JsonBean is the base class for uniform return of error codes, and ErrorCodeException is a custom exception.

Through @Transactional, transaction operations are realized.
Spring's AOP, declarative transaction management, defaults to rollback for unchecked exceptions. That is, by default, the RuntimeException() exception or its subclasses are rolled back; the checked exception, that is, the Exception can be caught by try{} and will not be rolled back. Therefore, for our custom exception, set it through rollbackFor, and it will be separately followed say
if we need to catch the exception, at the same time rollback by TransactionAspectSupport.currentTransactionStatus () setRollbackOnly (); manual rollback.
Use Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint(); to 
set the rollback point, use TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint); to rollback to savePoint.
3. Common configuration

Parameter name Function description
readOnly This attribute is used to set whether the current transaction is a read-only transaction, set to true to indicate read-only, false to indicate read-write, and the default value is false. For example: @Transactional(readOnly=true)
rollbackFor This attribute is used to set the exception class array that needs to be rolled back. When an exception in the specified exception array is thrown in the method, the transaction is rolled back. For example: specify a single exception class: @Transactional(rollbackFor=RuntimeException.class) specify multiple exception classes: @Transactional(rollbackFor={RuntimeException.class, Exception.class})
rollbackForClassName This attribute is used to set the exception class that needs to be rolled back The name array, when the exception in the specified exception name array is thrown in the method, the transaction is rolled back. For example: specify a single exception class name @Transactional(rollbackForClassName=”RuntimeException”) specify multiple exception class names: @Transactional(rollbackForClassName={"RuntimeException","Exception"})
noRollbackFor This attribute is used to set the rollback not required Exception class array, when the exception in the specified exception array is thrown in the method, the transaction will not be rolled back. For example: Specify a single exception class: @Transactional(noRollbackFor=RuntimeException.class) Specify multiple exception classes: @Transactional(noRollbackFor={RuntimeException.class, Exception.class})
noRollbackForClassName This attribute is used to set the array of exception class names that do not need to be rolled back. When an exception in the specified exception name array is thrown in the method, the transaction will not be rolled back. For example: specify a single exception class name: @Transactional(noRollbackForClassName=”RuntimeException”) specify multiple exception class names: @Transactional(noRollbackForClassName={“RuntimeException”,”Exception”})
propagation This attribute is used to set the propagation behavior of the transaction. For example: @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
isolation This property is used to set the transaction isolation level of the underlying database. The transaction isolation level is used to handle the case of multiple transactions concurrently. Usually, the default isolation level of the database can be used. Basically do not need to set
timeout This attribute is used to set the timeout seconds of the transaction, the default value is -1 which means never timeout
4. Transaction attributes

Transaction isolation level 
isolation level refers to the degree of isolation between several concurrent transactions. Five constants representing the isolation level are defined in the TransactionDefinition interface:

TransactionDefinition.ISOLATION_DEFAULT: This is the default value, which means that the default isolation level of the underlying database is used. For most databases, this value is usually TransactionDefinition.ISOLATION_READ_COMMITTED. 
TransactionDefinition.ISOLATION_READ_UNCOMMITTED: This isolation level means that a transaction can read data modified by another transaction but has not yet been committed. This level cannot prevent dirty reads, non-repeatable reads and phantom reads, so this isolation level is rarely used. For example, PostgreSQL does not actually have this level. 
TransactionDefinition.ISOLATION_READ_COMMITTED: This isolation level means that a transaction can only read data that has been committed by another transaction. This level can prevent dirty reads, which is also the recommended value in most cases. 
TransactionDefinition.ISOLATION_REPEATABLE_READ: This isolation level means that a transaction can execute a query multiple times during the entire process, and the records returned each time are the same. This level can prevent dirty reads and non-repeatable reads. 
TransactionDefinition.ISOLATION_SERIALIZABLE: All transactions are executed one by one, so that there is no interference between transactions, that is, this level can prevent dirty reads, non-repeatable reads, and phantom reads. But this will seriously affect the performance of the program. Normally, this level is not used either.

Transaction propagation behavior The 
so-called transaction propagation behavior means that if a transaction context already exists before starting the current transaction, there are several options to specify the execution behavior of a transactional method. The following constants representing the propagation behavior are included in the TransactionDefinition definition:

TransactionDefinition.PROPAGATION_REQUIRED: If there is a transaction currently, join the transaction; if there is no transaction currently, create a new transaction. It's the default value. 
TransactionDefinition.PROPAGATION_REQUIRES_NEW: Create a new transaction, if there is a transaction currently, then suspend the current transaction. 
TransactionDefinition.PROPAGATION_SUPPORTS: If there is currently a transaction, then join the transaction; if there is no current transaction, continue to run in a non-transactional manner. 
TransactionDefinition.PROPAGATION_NOT_SUPPORTED: Run in a non-transactional mode. If there is a transaction currently, the current transaction is suspended. 
TransactionDefinition.PROPAGATION_NEVER: Run in a non-transactional mode. If there is a transaction currently, an exception will be thrown. 
TransactionDefinition.PROPAGATION_MANDATORY: If there is a transaction currently, join the transaction; if there is no transaction currently, an exception will be thrown. 
TransactionDefinition.PROPAGATION_NESTED: If there is currently a 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 TransactionDefinition.PROPAGATION_REQUIRED.

Transaction timeout The 
so-called transaction timeout refers to the maximum time a transaction is allowed to execute. If the time limit is exceeded but the transaction has not been completed, the transaction is automatically rolled back. The int value is used to represent the timeout period in TransactionDefinition, and the unit is seconds. 
The default setting is the timeout value of the underlying transaction system. If the underlying database transaction system does not set a timeout value, then it is none and there is no timeout limit.

Transaction read-only property 
Read-only transaction is used when the client code is read-only but does not modify the data. Read-only transaction is used for optimization in specific scenarios, such as when using Hibernate. 
The default is read and write transactions.
 

Guess you like

Origin blog.csdn.net/qq_27828675/article/details/89514545