Spring transaction operations

I. Transaction (Concept)

1. What are transactions

  1. A transaction is the most basic unit of a database, a logical set of operations that either all succeed or, if one fails, all fail
  2. Typical scenario:
    • Lucy transferred 100 yuan to Mary
    • Lucy is 100 yuan less and Mary is 100 yuan more

2. Four properties of transactions (ACID)

  1. Atomicity
  2. Consistency
  3. Isolation
  4. “Durability”

Second, transaction operation

1. Introduction to Spring Transaction Management

  1. Transactions are added to the Service layer (business logic layer) in the JavaEE three-tier structure.

  2. Transaction management operations in Spring

    1. Programmatic transaction management: Writing code in code to manually open transactions
    2. Declarative transaction management: Configure and enable transactions faceted
  3. Declarative transaction management

    1. Annotation-based approach (use)
    2. Based on XML configuration files
  4. Declarative transaction management in Spring, using AOP principles at the bottom

  5. Spring transaction management API

    • Provides an interface that represents the transaction manager and provides different implementation classes for different frameworks

2. Annotation declarative transaction management

  1. Configure the transaction manager in the Spring configuration file

    <! Create transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <! Inject data source -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    Copy the code
  2. In the Spring configuration file, turn on transaction annotations

    1. Introduce the namespace TX in the Spring configuration file

      
                
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
      Copy the code
    2. Open transaction annotations

      <! -- Enable transaction annotations -->
      <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
      Copy the code
  3. Add transaction annotations above the Service class (or above the methods in the Service class)

    1. Transaction. This annotation can be added to a class or method

    2. If you add this annotation to a class, all the methods in the class add transactions

    3. If you add this annotation to the method, you simply add a transaction to the method

      @Service
      @Transaction
      public class UserService {... }Copy the code

3. Set parameters for declarative transaction management

  1. Add the @Transaction annotation to the Service class declaration, which allows you to configure Transaction parameters

  2. Propagation: Transaction propagation behavior

    1. ** Transaction propagation behavior: ** How are transactions managed when multiple transaction methods are invoked directly

    2. Transaction method: The operation to change the books of a database table

    3. The Spring framework has seven transactional propagation behaviors, focusing on REQUIRED and REQUIRES_NEW

      • REQUIRED: If the add method itself has a transaction, the update method uses the transaction in the current add method after calling the update method. If the Add method does not have a transaction itself, a new transaction is created after the update method is called

      • REQUIRES_NEW: The update method is called with the add method. The update method creates a new transaction whether the Add method has a transaction or not. If the add method’s transaction is running, the update method’s transaction is suspended first

  3. Isolation: transaction isolation level

    1. Transactions have a property called isolation, where operations between multiple transactions have no impact. Many problems can arise if isolation is not considered
    2. There are three problems: dirty reads, unrepeatable reads, and phantom reads
    3. Dirty read: Data read from one transaction to another uncommitted transaction

    1. ** Non-repeatable read: ** Inconsistent results from two queries in one transaction (for update operations)

    1. ** Phantom reading: ** Inconsistent results from two queries in one transaction (for INSERT operations)

    2. How to solve these problems?

      • Resolve read problems by setting transaction isolation level

      • SQL standard transaction isolation levels include read uncommitted, read Committed, repeatable read (default in MySQL), and serialization

        • Read uncommitted: Changes made by a transaction can be seen by other transactions before it is committed
        • Read Committed: After a transaction commits, its changes can’t be seen by other transactions
        • Repeatable read: The data seen during the execution of a transaction is always the same as the data seen when the transaction is started
        • Serialization: For the same row, write will add write lock, read will add read lock. When a read-write lock conflict occurs, the last accessed transaction must wait for the previous transaction to complete before execution can continue

  4. Timeout: indicates the timeout period

    • Transactions need to commit within a certain amount of time, and if they don’t, they are rolled back
    • The default value is -1, and the setting time is measured in seconds
  5. ReadOnly: Indicates whether it is read-only

    • Read: query operation Write: Add, modify, and delete
    • ReadOnly The default value is false, indicating that it can be read or written
    • ReadOnly is set to true. Only read operations, that is, queries, can be performed
  6. RollbaclFor: rolled back

    • Sets which exceptions occur for transaction rollback
  7. NoRollbackFor: does not roll back

    • Sets which exceptions do not roll back transactions

XML declarative transaction management

  • Do this in the Spring configuration file

    1. Configure the transaction manager

      <! Create transaction manager -->
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"></property>
      </bean>
      Copy the code
    2. Configure notification

      <! -- 2. Configure notifications -->
      <tx:advice id="txadvice">
          <! -- Set transaction parameters -->
          <tx:attributes>
              <tx:method name="accountMoney" propagation="REQUIRED"/>
          </tx:attributes>
      </tx:advice>
      Copy the code
    3. Configure pointcuts and facets

      <! -- 3. Configure pointcuts and facets -->
      <aop:config>
          <! Configure pointcuts -->
          <aop:pointcut id="pt" expression="execution(* com.atguigu.spring5.service.UserService.*(..) )"/>
          <! -- Configuration section -->
          <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
      </aop:config>
      Copy the code

5. Fully annotated declarative transaction management

  • Creating a Configuration Class

    @Configuration / / configuration class
    @ComponentScan(basePackages = "com.atguigu") // Enable component scanning
    @EnableTransactionManagement // Start the transaction
    public class TxConfig {
    
        @Bean
        public DruidDataSource getDruidDataSource(a) {
            DruidDataSource druidDataSource = new DruidDataSource();
    
            druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring");
            druidDataSource.setUsername("root");
            druidDataSource.setPassword("root");
    
            return druidDataSource;
        }
    
        // Create JdbcTemplate object
        @Bean(value = "jdbcTemplate")
        public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
    
            jdbcTemplate.setDataSource(dataSource);
    
            return jdbcTemplate;
        }
    
        // Create transaction manager
        @Bean
        public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
            DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
    
            dataSourceTransactionManager.setDataSource(dataSource);
    
            returndataSourceTransactionManager; }}Copy the code