Spring Boot tutorial (6): spring boot transaction management

1. Introduction to transaction management

All data access technologies are inseparable from transaction processing, otherwise it will cause data inconsistency. In the current enterprise-level application development, transaction management is indispensable. A database transaction refers to a series of operations performed as a single logical unit of work, either completely executed or not executed at all. Transaction processing can ensure that unless all operations within the transactional unit are successfully completed, data-oriented resources will not be permanently updated.

By combining a set of related operations into a unit that either all succeeds or all fails, you can simplify error recovery and make your application more reliable. For a logical unit of work to become a transaction, it must meet the so-called ACID (atomicity, consistency, isolation, and durability) attributes. The transaction is the logical unit of work in the operation of the database, and the transaction management subsystem in the database is responsible for the processing of the transaction .

The first thing to be clear is that the Spring Boot transaction mechanism is essentially Spring's transaction mechanism. It uses a unified mechanism to process transactions from different data access technologies, but Spring Boot performs partial processing based on the automatic configuration feature to save developers The configuration works.

Spring transaction management is divided into two ways:

  • Programmatic transactions refer to the implementation of transactions through coding.
  • Declarative transactions, based on AOP, decouple specific business logic from transaction processing. This is the recommended way.

Two, declarative affairs

The declarative transaction is built on the AOP mechanism. 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 of the target method after the target method is executed. The biggest advantage of declarative transaction is that the specific business logic and transaction processing are decoupled through the AOP mechanism, and there is no need to manage the transaction by programming, so there is no need to dope transaction management code in the business logic code, so in actual use Declarative transactions are used more.

There are two ways of declarative transactions: one is to make the relevant transaction rule declaration in the XML configuration file; the other is based on the @Transactional annotation (@Transactional annotation is from the org.springframework.transaction.annotation package). You can apply transaction rules to business logic.

In SpringBoot, it is recommended to use the annotation @Transactional to control the transaction. You only need to add the @Transactional annotation to the method or class that requires transaction management. Next, let's explain it through the code.

First, create a new service package as a business code package. Transaction processing is generally done in the service layer. Of course, it can also be processed in the controller layer. However, it is recommended to process in the business layer. Then, create a new TransactionTestService class in the package.

package com.wang.service;

import com.wang.dao.AuthorDao;
import com.wang.entity.Author;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class TransactionTestService {
    
    
    @Resource
    AuthorDao authorDao;

    public Boolean test1() {
    
    
        Author author = new Author();
       author.setPassword("test1-password");
       author.setName("test1_name");
       author.setId("test1_id");
        // 在数据库表中新增一条记录
        authorDao.addAuthor(author);
        // 发生异常
        System.out.println(1/0);
        return true;
    }

    @Transactional
    public Boolean test2() {
    
    
        Author author = new Author();
        author.setPassword("test2-password");
        author.setName("test2_name");
        author.setId("test2_id");
        // 在数据库表中新增一条记录
        authorDao.addAuthor(author);
        // 发生异常
        System.out.println(1/0);
        return true;
    }
}

First, add @Service to the class to register it in the IOC container for management, then inject the UserDao object to implement subsequent data layer operations, and finally implement two business methods test1() and test2(). The two implementations are similar, but two The user object name and password string added by the method are different, and the @Transactional annotation is added to the test2() method, while the test1() method is not added. In the method, we have added a code to remove the number 1 from the number 0, this code must have an exception, we use this to simulate whether the transaction can be successful when an exception occurs.

According to normal understanding, once an exception occurs after the SQL statement is executed, the database change will be rolled back by the transaction. Normally, there will be test1 data but no test2 data in the database, because the test1() method is not included In transaction management, the test2() method will be processed by the transaction manager due to the @Transactional annotation.

Those who are interested can write their own code to test the effect.

In addition, @Transactional can be annotated not only on methods, but also on classes. When annotated on a class, it means that all public methods of this class are open transactions. If @Transactional annotations are used at both the class level and the method level, the annotations used at the class level will override the method level annotations.

Guess you like

Origin blog.csdn.net/Tracycoder/article/details/113940200