Spring integrated transaction control of mybatis

1. Transaction control of mybatis

  1. Mybatis transaction: JDBC|Manage will not automatically commit by default.
  2. Spring integrated mybatis transaction : the transaction is automatically submitted by default.
    Package required: mybatis-spring-xxx.jar package; spring-tx-xxxx.jar package

Essence: hand over the affairs to spring management

2. Transaction control

2.1 Affairs
2.1.1 Transaction concept

Transaction : A set of operations logically, either all succeed or all fail.

The purpose of things is to solve the problem of [data inconsistency].

2.1.2 Transaction characteristics: (ACID)

Atomicity (A): Transaction indivisible
Consistency (C): Data integrity remains consistent before and after the transaction is executed.
Isolation (I): When a transaction is executed, it should not be disturbed by other transactions.
Persistence (D) : Once finished, the data will be permanently saved to the database.

2.1.3 Three types of transaction reading problems

If isolation is not considered, the transaction consists of three types of read problems:
dirty read : one transaction reads uncommitted data from another transaction.
Non-repeatable read : One transaction reads to another transaction has committed data (update), resulting in inconsistent results of multiple queries of one transaction.
Virtual read : A transaction reads data submitted by another transaction (insert), which results in inconsistent results of multiple queries of a transaction.
Note: Concurrent access lost update problem: Java (lock)/database (lock)

2.1.4 Transaction isolation level:

Setting the isolation level of the transaction can effectively solve the three types of reading problems caused by the transaction characteristics to a certain extent:

  1. Uncommitted Reading: The above situations may happen.
  2. Submitted reads: Avoid dirty reads, but do not repeat reads. Virtual reads are possible.
  3. Repeatable read: Avoid dirty reads, non-repeatable reads, but virtual reads may occur.
  1. Serializable: Avoid all the above situations. The system throughput is very low.

2.2 Transaction Management in Spring

Three-tier architecture: web layer: Servlet/jsp---->service layer—>dao/mapper layer
Layered development: the transaction is in the Service layer.

2.2.1. Spring provides transaction management API
2.2.1.1.PlatformTransactionManager: Platform transaction manager.
  1. commit(TransactionStatus status)
  2. getTransaction(TransactionDefinition definition)
  3. rollback(TransactionStatus status)
2.2.1.2. TransactionDefinition: Transaction Definition
  1. ISOLation_XXX: Transaction isolation level.
  2. PROPAGATION_XXX: Transaction propagation behavior. (Not in JDBC, in order to solve actual development problems.)
  3. Timeout: Expiration time
2.2.1.3. TransactionStatus: Transaction status
  1. Is there a save point
  2. Is it a new transaction
  3. Whether the transaction has been committed
2.2.1.4. Relationship between the three

PlatformTransactionManager sets transaction-related information management transactions through TransactionDefinition. During the transaction management process, some transaction statuses are generated: the status is recorded by TransactionStatus.

2.2.2 Detailed API:

Spring provides different PlatformTransactionManager interface implementations for different persistence frameworks


  1. Used when org.springframework.jdbc.datasource.DataSourceTransactionManager uses Spring JDBC or iBatis for persistent data

  2. Used when org.springframework.orm.hibernate3.HibernateTransactionManager uses Hibernate3.0 version for persistent data

  3. Used when org.springframework.orm.jpa.JpaTransactionManager uses JPA for persistence
  4. org.springframework.jdo.JdoTransactionManager is used
    when the persistence mechanism is Jdo
  5. org.springframework.transaction.jta.JtaTransactionManager
    uses a JTA implementation to manage transactions, which must be used when a transaction spans multiple resources

2. Implementation of spring transaction

1) Manual (programming) transaction (demo understanding)

Step 1: Which methods of the business layer require transactions (hacking).
UserInfoServiceImpl1.zz(int from ,int to ,int money);
Step 2: Configure the transaction manager in xml (different orm framework transaction management methods are different)

            (orm框架:mybatis,hibernate,jpa,jdbcTemplate......)
        <bean  id="txTransaction" class="org.springframework.jdbc.datasource.DataSourceTransactionManager  ">
            <property name="dataSource" ref="dataSource"/>
        </bean>

Step 3: Define the TransatcionTemplate transaction template class
new TransatcionTemplate (transaction manager) in the business class ;

Step 4: In the method that requires transaction management

                transactionTemplate.execute(new TransactionCallbackWithoutResult() {
    
    

                protected void doInTransactionWithoutResult(TransactionStatus status) {
    
    
                    try {
    
    
                        updateOperation1();//持久层操作1   扣二狗子的300
                        updateOperation2();//持久层操作2   增加付自强300
                    } catch (SomeBusinessException ex) {
    
    
                        status.setRollbackOnly();
                    }
                }
            });

Step 5: Test, call the method of the business class

    @Autowired
    
    private IUserInfoService iUserInfoService;
    @Test
    public void testZZ() {
    
    
        iUserInfoService.zz(1, 200, 300);//没有代理  调用的就是目标对象的目标方法
    }
2) Declarative affairs (development)
第1步:业务的层的哪些方法需要事务(黑客)。
UserInfoServiceImpl1.zz(int from ,int to ,int money);

Step 2: Configure the transaction manager in xml (different orm framework transaction management methods are different)

       (orm框架:mybatis,hibernate,jpa,jdbcTemplate......)
        <bean  id="txTransaction" class="org.springframework.jdbc.datasource.DataSourceTransactionManager  ">
            <property name="dataSource" ref="dataSource"/>
        </bean>
  第3步:xml配置中定义切面
    <!-- 1.切面 -->
    <tx:advice id="ndAdvice"  transaction-manager="txTransaction">
            <tx:attributes>
                <!-- 哪个方法需要使用什么事务:哪个屁眼需要插入黑板刷
                zz*:所有以zz开始的方法名的所有方法
                *zz: 所有以zz结束的方法名的所有方法
                -->
                <tx:method name="zz*" />
                <!-- *  其他方法使用默认事务   事务是只读的,就表名事务内不能对数据进行更新。-->
                <tx:method name="*"  read-only="true"/>
        </tx:attributes>
    </tx:advice>

Step 4: The xml configuration automatically generates the proxy object of the business method according to the cut point + enhancement

3) Spring annotation-based transaction management

Step 1: Enable annotation transaction

<tx:annotation-driven transaction-manager="transactionManager"/> 

Step 2: Use @Transactional to indicate the method that needs transaction

Step 3: Test

Guess you like

Origin blog.csdn.net/weixin_46822085/article/details/108877231