【Spring】Spring 对事务的支持

一、事务概述

什么是事务?

在一个业务流程当中,通常需要多条DML(insert delete update)语句共同联合才能完成,这多条DML语句必须同时成功,或者同时失败,这样才能保证数据的安全

  • 多条DML要么同时成功,要么同时失败,这叫做事务

  • 事务:Transaction(tx)

事务的四个处理过程:

  • 第一步:开启事务 (start transaction)

  • 第二步:执行核心业务代码

  • 第三步:提交事务(如果核心业务处理过程中没有出现异常)(commit transaction)

  • 第四步:回滚事务(如果核心业务处理过程中出现异常)(rollback transaction)

事务的四个特性:

  • A 原子性:事务是最小的工作单元,不可再分

  • C 一致性:事务要求要么同时成功,要么同时失败。事务前和事务后的总量不变

  • I 隔离性:事务和事务之间因为有隔离性,才可以保证互不干扰

  • D 持久性:持久性是事务结束的标志

二、事务场景 

以银行账户转账为例学习事务。

两个账户 act-001和 act-002,act-001账户向 act-002 账户转账 10000,必须同时成功,或者同时失败(一个减成功,一个加成功, 这两条 update 语句必须同时成功,或同时失败)

连接数据库的技术采用 Spring 框架的 JdbcTemplate

项目依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.qiu</groupId>
    <artifactId>spring-012-tx-bank</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!--spring context-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.23</version>
        </dependency>
        <!--spring jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.23</version>
        </dependency>
        <!--mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.13</version>
        </dependency>
        <!--@Resource注解-->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

第一步:数据库准备

表结构:

表数据:  

第二步:创建包结构

org.qiu.bank.pojo

org.qiu.bank.service

org.qiu.bank.service.impl

org.qiu.bank.dao

org.qiu.bank.dao.impl

第三步:准备实体类

package org.qiu.bank.pojo;

/**
 * @author 秋玄
 * @version 1.0
 * @email qiu_2022@aliyun.com
 * @project Spring
 * @package org.qiu.bank.pojo
 * @date 2022-11-29-22:18
 * @since 1.0
 */
public class Account {
    private String actno;
    private Double balance;

    public Account() {
    }

    public Account(String actno, Double balance) {
        this.actno = actno;
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "actno='" + actno + '\'' +
                ", balance=" + balance +
                '}';
    }

    public String getActno() {
        return actno;
    }

    public void setActno(String actno) {
        this.actno = actno;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }
}

第四步:编写持久层  

package org.qiu.bank.dao;

import org.qiu.bank.pojo.Account;

/**
 * @author 秋玄
 * @version 1.0
 * @email qiu_2022@aliyun.com
 * @project Spring
 * @package org.qiu.bank.dao
 * @date 2022-11-29-22:21
 * @since 1.0
 */
public interface AccountDao {

    /**
     * 根据账号查询账户信息
     * @param actno 账号
     * @return      账户对象
     */
    Account selectByActno(String actno);

    /**
     * 更新账户信息
     * @param act
     * @return
     */
    int update(Account act);
}
package org.qiu.bank.dao.impl;

import org.qiu.bank.dao.AccountDao;
import org.qiu.bank.pojo.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * @author 秋玄
 * @version 1.0
 * @email qiu_2022@aliyun.com
 * @project Spring
 * @package org.qiu.bank.dao.impl
 * @date 2022-11-29-22:25
 * @since 1.0
 */
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Resource(name = "jdbcTemplatel")
    private JdbcTemplate jdbcTemplatel;

    @Override
    public Account selectByActno(String actno) {
        String sql = "select actno, balance from t_act where actno = ?";
        Account account = jdbcTemplatel.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), actno);
        return account;
    }

    @Override
    public int update(Account act) {
        String sql = "update t_act set balance = ? where actno = ?";
        int count = jdbcTemplatel.update(sql, act.getBalance(), act.getActno());
        return count;
    }
}

第五步:编写业务层  

package org.qiu.bank.service;

/**
 * @author 秋玄
 * @version 1.0
 * @email qiu_2022@aliyun.com
 * @project Spring
 * @package org.qiu.bank.service
 * @date 2022-11-29-22:30
 * @since 1.0
 */
public interface AccountService {

    /**
     * 转账
     * @param fromActno 转出账户
     * @param tiActno   转入账户
     * @param money     转账金额
     */
    void transfer(String fromActno, String tiActno, double money);

}
package org.qiu.bank.service.impl;

import org.qiu.bank.dao.AccountDao;
import org.qiu.bank.pojo.Account;
import org.qiu.bank.service.AccountService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 秋玄
 * @version 1.0
 * @email qiu_2022@aliyun.com
 * @project Spring
 * @package org.qiu.bank.service.impl
 * @date 2022-11-29-22:33
 * @since 1.0
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Resource(name = "accountDao")
    private AccountDao accountDao;

    @Override
    public void transfer(String fromActno, String toActno, double money) {
        // 查询转出账户余额是否足够
        Account fromAct = accountDao.selectByActno(fromActno);

        if (fromAct.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }

        // 余额充足
        Account toAct = accountDao.selectByActno(toActno);

        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);

        // 数据库更新
        int count = accountDao.update(fromAct);
        count += accountDao.update(toAct);

        if (count != 2){
            throw  new RuntimeException("转账失败");
        }
    }
}

第六步:编写 Spring 配置文件  

<?xml version="1.0" encoding="UTF-8"?>
<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"
       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">

    <context:component-scan base-package="org.qiu.bank"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mvc"/>
        <property name="username" value="root"/>
        <property name="password" value="mysql"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

第七步:编写测试程序  

package org.qiu.bank.test;

import org.junit.Test;
import org.qiu.bank.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author 秋玄
 * @version 1.0
 * @email qiu_2022@aliyun.com
 * @project Spring
 * @package org.qiu.bank.test
 * @date 2022-11-29-22:48
 * @since 1.0
 */
public class BankTest {

    @Test
    public void testSpringTx(){
        ApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");
        AccountService service = app.getBean("accountService", AccountService.class);
        try {
            service.transfer("act001","act002",10000.0);
            System.out.println("转账成功");
        } catch (Exception e){
            e.printStackTrace();
        }
    }

}

运行结果:  

模拟异常

package org.qiu.bank.test;

import org.junit.Test;
import org.qiu.bank.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author 秋玄
 * @version 1.0
 * @email qiu_2022@aliyun.com
 * @project Spring
 * @package org.qiu.bank.test
 * @date 2022-11-29-22:48
 * @since 1.0
 */
public class BankTest {

    @Test
    public void testSpringTx(){
        ApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");
        AccountService service = app.getBean("accountService", AccountService.class);
        try {
            service.transfer("act001","act002",10000.0);
            System.out.println("转账成功");
        } catch (Exception e){
            e.printStackTrace();
        }
    }

}

运行效果:  

金额丢失了一万!!!!!!!!!! 

三、Spring 对事务的支持

Spring 实现事务的两种方式:

  • 编程式事务

  • 通过编写代码的方式来实现事务的管理。

  • 声明式事务

    • 基于注解方式

  • 基于XML配置方式

Spring 事务管理 API

Spring 对事务的管理底层实现方式是基于 AOP 实现的,采用 AOP 的方式进行了封装。

所以 Spring 专门针对事务开发了一套 API,API 的核心接口如下:

PlatformTransactionManager 接口:Spring 事务管理器的核心接口

Spring6 中它有两个实现:

  • DataSourceTransactionManager:支持 JdbcTemplate、MyBatis、Hibernate 等事务管理

  • JtaTransactionManager:支持分布式事务管理

如果要在 Spring6 中使用 JdbcTemplate,就要使用 DataSourceTransactionManager 来管理事务(Spring内置写好了,可以直接用)

声明式事务之注解实现方式

第一步:在spring配置文件中配置事务管理器

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

第二步:在spring配置文件中引入tx命名空间  

<?xml version="1.0" encoding="UTF-8"?>
<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: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/tx 
                           http://www.springframework.org/schema/tx/spring-tx.xsd">

第三步:在spring配置文件中配置“事务注解驱动器”,开始注解的方式控制事务 

<!-- 事务注解驱动器 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

第四步:在service类上或方法上添加@Transactional注解

在类上添加该注解,该类中所有的方法都有事务

在某个方法上添加该注解,表示只有这个方法使用事务

@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
    // ......
}

当前数据库表中的数据:  

执行测试程序:  

虽然出现异常了,再次查看数据库表中数据:  

事务的全注解式开发

编写一个类来代替配置文件

package org.qiu.bank.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author 秋玄
 * @version 1.0
 * @email qiu_2022@aliyun.com
 * @project Spring
 * @package org.qiu.bank.config
 * @date 2022-11-30-21:16
 * @since 1.0
 */
@Configuration
@ComponentScan("org.qiu.bank")
@EnableTransactionManagement
public class SpringConfig {

    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mvc");
        dataSource.setUsername("root");
        dataSource.setPassword("mysql");
        return dataSource;
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}
@Test
public void testAnnotation(){
    ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
    AccountService service = app.getBean("accountService", AccountService.class);
    try{
        service.transfer("act002","act001",10000.0);
        System.out.println("转账成功");
    } catch (Exception e){
        e.printStackTrace();
    }
}

运行效果:  

声明式事务之 XML 实现方式

配置步骤:

  • 第一步:配置事务管理器

  • 第二步:配置通知

  • 第三步:配置切面

添加依赖:

<!--aspectj-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.13.RELEASE</version>
</dependency>

Spring配置文件如下: 

<?xml version="1.0" encoding="UTF-8"?>
<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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="org.qiu.bank"/>

    <!-- 事务注解驱动器 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mvc"/>
        <property name="username" value="root"/>
        <property name="password" value="mysql"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
            <tx:method name="del*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
            <tx:method name="transfer*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
        </tx:attributes>
    </tx:advice>

    <!--配置切面-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* org.qiu.bank.service..*(..))"/>
        <!--切面 = 通知 + 切点-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

</beans>

将AccountServiceImpl类上的@Transactional注解删除

测试程序:

@Test
public void testSpringTx(){
    ApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");
    AccountService service = app.getBean("accountService", AccountService.class);
    try {
        service.transfer("act001","act002",10000.0);
        System.out.println("转账成功");
    } catch (Exception e){
        e.printStackTrace();
    }
}

运行效果:  

四、事务属性

事务中的重点属性:

  • 事务传播行为

  • 事务隔离级别

  • 事务超时

  • 只读事务

  • 设置出现哪些异常回滚事务

  • 设置出现哪些异常不回滚事务

事务传播行为

什么是事务的传播行为?

在 service 类中有 a() 方法和 b() 方法,a() 方法上有事务,b() 方法上也有事务,当 a() 方法执行过程中调用了 b() 方法,事务是如何传递的?合并到一个事务里?还是开启一个新的事务?这就是事务传播行为。

事务传播行为在 Spring 框架中被定义为枚举类型:

一共有七种传播行为:

  • REQUIRED:支持当前事务,如果不存在就新建一个(默认)【没有就新建,有就加入】

  • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行【有就加入,没有就不管了】

  • MANDATORY:必须运行在一个事务中,如果当前没有事务正在发生,将抛出一个异常【有就加入,没有就抛异常】

  • REQUIRES_NEW:开启一个新的事务,如果一个事务已经存在,则将这个存在的事务挂起【不管有没有,直接开启一个新事务,开启的新事务和之前的事务不存在嵌套关系,之前事务被挂起】

  • NOT_SUPPORTED:以非事务方式运行,如果有事务存在,挂起当前事务【不支持事务,存在就挂起】

  • NEVER:以非事务方式运行,如果有事务存在,抛出异常【不支持事务,存在就抛异常】

  • NESTED:如果当前正有一个事务在进行中,则该方法应当运行在一个嵌套式事务中。被嵌套的事务可以独立于外层事务进行提交或回滚。如果外层事务不存在,行为就像 REQUIRED 一样【有事务的话,就在这个事务里再嵌套一个完全独立的事务,嵌套的事务可以独立的提交和回滚。没有事务就和 REQUIRED 一样】

在代码中设置事务的传播行为:

@Transactional(propagation = Propagation.REQUIRED)

事务隔离级别

事务隔离级别类似于教室A和教室B之间的那道墙,隔离级别越高表示墙体越厚。隔音效果越好。

数据库中读取数据存在的三大问题(三大读问题):

  • 脏读:读取到没有提交到数据库的数据,叫做脏读

  • 不可重复读:在同一个事务当中,第一次和第二次读取的数据不一样

  • 幻读:读到的数据是假的

事务隔离级别包括四个级别:

  • 读未提交:READ_UNCOMMITTED

    • 这种隔离级别,存在脏读问题,所谓的脏读(dirty read)表示能够读取到其它事务未提交的数据

  • 读提交:READ_COMMITTED 【Oracle 默认隔离级别】

    • 解决了脏读问题,其它事务提交之后才能读到,但存在不可重复读问题

  • 可重复读:REPEATABLE_READ 【MySQL默认隔离级别】

    • 解决了不可重复读,可以达到可重复读效果,只要当前事务不结束,读取到的数据一直都是一样的。但存在幻读问题

  • 序列化:SERIALIZABLE

    • 解决了幻读问题,事务排队执行。不支持并发

隔离级别脏读不可重复读幻读
读未提交
读提交
可重复读
序列化

隔离级别在 Spring 中以枚举类型存在:

@Transactional(isolation = Isolation.READ_COMMITTED)

事务超时

 @Transactional(timeout = 10)

以上代码表示设置事务的超时时间为 10 秒

表示超过 10 秒如果该事务中所有的 DML 语句还没有执行完毕的话,最终结果会选择回滚

默认值 -1,表示没有时间限制

这里有个坑,事务的超时时间指的是哪段时间?

在当前事务当中,最后一条DML语句执行之前的时间,如果最后一条DML语句后面很有很多业务逻辑,这些业务代码执行的时间不被计入超时时间

以下代码不会被计入超时时间:

@Transactional(timeout = 10) // 设置事务超时时间为10秒。
public void save(Account act) {
    accountDao.insert(act);
    // 睡眠一会
    try {
        Thread.sleep(1000 * 15);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

以下代码会被计入超时时间:  

@Transactional(timeout = 10) // 设置事务超时时间为10秒。
public void save(Account act) {
    // 睡眠一会
    try {
        Thread.sleep(1000 * 15);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    accountDao.insert(act);
}

当然,如果想让整个方法的所有代码都计入超时时间的话,可以在方法最后一行添加一行无关紧要的DML语句。  

只读事务  

@Transactional(readOnly = true)

将当前事务设置为只读事务,在该事务执行过程中只允许select语句执行,delete insert update均不可执行

该特性的作用是:启动spring的优化策略,提高select语句执行效率

如果该事务中确实没有增删改操作,建议设置为只读事务

设置哪些异常回滚事务

@Transactional(rollbackFor = RuntimeException.class)

表示只有发生 RuntimeException 异常或该异常的子类异常才回滚

设置哪些异常不回滚

@Transactional(noRollbackFor = NullPointerException.class)

表示发生NullPointerException或该异常的子类异常不回滚,其他异常则回滚  

一  叶  知  秋,奥  妙  玄  心

  • 36
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QX_Java_Learner

祝老板生意兴隆,财源广进!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值