spring(7)-事务

发布于:2024-04-11 ⋅ 阅读:(171) ⋅ 点赞:(0)

1、 事务概述

● 什么是事务
○ 在一个业务流程当中,通常需要多条DML(insert delete update)语句共同联合才能完成,这多条DML语句必须同时成功,或者同时失败,这样才能保证数据的安全。
○ 多条DML要么同时成功,要么同时失败,这叫做事务。
○ 事务:Transaction(tx)
● 事务的四个处理过程:
○ 第一步:开启事务 (start transaction)
○ 第二步:执行核心业务代码
○ 第三步:提交事务(如果核心业务处理过程中没有出现异常)(commit transaction)
○ 第四步:回滚事务(如果核心业务处理过程中出现异常)(rollback transaction)
● 事务的四个特性:
○ A 原子性:事务是最小的工作单元,不可再分。
○ C 一致性:事务要求要么同时成功,要么同时失败。事务前和事务后的总量不变。
○ I 隔离性:事务和事务之间因为有隔离性,才可以保证互不干扰。
○ D 持久性:持久性是事务结束的标志。

2、spring对事务的支持

两种方式:
● 编程式事务
○ 通过编写代码的方式来实现事务的管理。(比如自己写切面类
● 声明式事务
○ 基于注解方式
○ 基于XML配置方式

2.1 spring事务管理API

spring实现了事务的接口,可以帮助我们管理事务。其实底层也是基于AOP切面编程实现的。

Spring对事务的管理底层实现方式是基于AOP实现的。采用AOP的方式进行了封装。所以Spring专门针对事务开发了一套API,API的核心接口如下:
在这里插入图片描述
PlatformTransactionManager接口:spring事务管理器的核心接口。在Spring6中它有两个实现:
● DataSourceTransactionManager:支持JdbcTemplate、MyBatis、Hibernate等事务管理。
● JtaTransactionManager:支持分布式事务管理。
如果要在Spring6中使用JdbcTemplate,就要使用DataSourceTransactionManager来管理事务。(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">


</beans>

配置事务管理器
dataSource 是一个数据源 可以配置自己的数据源

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

spring配置文件中配置“事务注解驱动器”,开始注解的方式控制事务。

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

在类上添加注解
● 在service类上或方法上添加@Transactional注解
在类上添加该注解,该类中所有的方法都有事务。在某个方法上添加该注解,表示只有这个方法使用事务。

2.2 事务属性

事务属性包括哪些
在这里插入图片描述
事务中的重点属性:
● 事务传播行为
● 事务隔离级别
● 事务超时
● 只读事务
● 设置出现哪些异常回滚事务
● 设置出现哪些异常不回滚事务

2.2.1 事务传播行为

什么是事务的传播行为?
在service类中有a()方法和b()方法,a()方法上有事务,b()方法上也有事务,当a()方法执行过程中调用了b()方法,事务是如何传递的?合并到一个事务里?还是开启一个新的事务?这就是事务传播行为。
事务传播行为在spring框架中被定义为枚举类型:
在这里插入图片描述
一共有七种传播行为:
REQUIRED:支持当前事务,如果不存在就新建一个(默认)【没有就新建,有就加入】
(内部事务失败回滚了 外部事务无法执行,即使捕捉到了异常,外部事物也无法继续。)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行【有就加入,没有就不管了】
MANDATORY:必须运行在一个事务中,如果当前没有事务正在发生,将抛出一个异常【有就加入,没有就抛异常】
REQUIRES_NEW:开启一个新的事务,如果一个事务已经存在,则将这个存在的事务挂起【不管有没有,直接开启一个新事务,开启的新事务和之前的事务不存在嵌套关系,之前事务被挂起】(内部发生异常,外部事物依然可以执行。是两个相互独立的事务,互不影响。外部事务回滚不会影响到内部事务。)
NOT_SUPPORTED:以非事务方式运行,如果有事务存在,挂起当前事务【不支持事务,存在就挂起】
NEVER:以非事务方式运行,如果有事务存在,抛出异常【不支持事务,存在就抛异常】
NESTED:如果当前正有一个事务在进行中,则该方法应当运行在一个嵌套式事务中。被嵌套的事务可以独立于外层事务进行提交或回滚。如果外层事务不存在,行为就像REQUIRED一样。【有事务的话,就在这个事务里再嵌套一个完全独立的事务,嵌套的事务可以独立的提交和回滚。没有事务就和REQUIRED一样。】(内部事务是外部事务的一个子事务,如果外部事务回滚,则内部事务也回滚,内部事务回滚不会影响到外部事务.)

2.2.2 案例

 @Resource(name = "accService2")
    private AccountService accountService;
  @Transactional(propagation = Propagation.REQUIRED)
    public  int insert1(){
        Account account=new Account("act008",10000.0);
        int i = accountDao.insert(account);
        i+=accountService.insert1();
        return i;
    }
 @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int insert1() {
        Account account=new Account("act007",10000.0);
        int i = accountDao.insert(account);
        return 0;
    }

2.2.2.1 REQUIRED

REQUIRED
在这里插入图片描述
通过日志输出,我们可以看出REQUIRED,没有事务,自动创建一个新的,有时,就加入。模拟异常如果事务有异常,则都回滚,无法提交。即使外部处理了异常,也无法继续执行。

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int insert1() {
        Account account=new Account("act009",10000.0);
        String a=null;
        a.toString();
        int i = accountDao.insert(account);
        return i;
    }
2.2.2.2 REQUIRES_NEW

`REQUIRES_NEW

 @Resource(name = "accService2")
    private AccountService accountService;

    @Transactional(propagation = Propagation.REQUIRED)
    public  int insert1(){
        Account account=new Account("act0010",10000.0);
        int i = accountDao.insert(account);
        i+=accountService.insert1();
        System.out.println("aaa");
        return i;
    }
  @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public int insert1() {
        Account account=new Account("act009",10000.0);
        String a=null;
        a.toString();
        int i = accountDao.insert(account);
        return i;
    }

在这里插入图片描述
是两个相互独立的事务,内部执行,外部挂起,内部回滚,接着回到外部事务处,但是由于外部事务没有处理异常,所以也回滚了。

  @Transactional(propagation = Propagation.REQUIRED)
    public  int insert1(){
        Account account=new Account("act0010",10000.0);
        int i = accountDao.insert(account);
        try {
            i += accountService.insert1();
            System.out.println("aaa");
        }
        catch (Exception e){
            System.out.println("错误");
        }
        return i;
    }

如果外部处理了异常 则外部可以正常执行,只有内部事务回滚
插入成功.
在这里插入图片描述

在这里插入图片描述

如果内部事务正常,则内部事务可以独立提交,外部事务回滚不影响内部事务

2.2.2.3 NESTED

NESTED

 @Transactional(propagation = Propagation.REQUIRED)
    public  int insert1(){
        Account account=new Account("act0010",10000.0);
        int i = accountDao.insert(account);

         i += accountService.insert1();
          System.out.println("aaa");

        String a=null;
        a.toString();

        return i;
    }
  @Transactional(propagation = Propagation.NESTED)
    @Override
    public int insert1() {
        Account account=new Account("act009",10000.0);

        int i = accountDao.insert(account);
        return i;
    }

在这里插入图片描述
NESTED 内部事务是外部事物的一个子事务,外部回滚则内部也回滚。
如果内部异常,且外部没有处理异常,则外部也无法正常执行,如果内部异常,但是外部事务处理了异常,则外部事务可以正常提交。
自己总结:REQUIRED是一个事务,即使外部处理了异常,也都要回滚。REQUIRED_NEW,是两个独立的事务,外部异常,不影响内部正常提交。NESTED子事务,外部回滚,内部就要回滚,但是内部回滚,只要外部处理了,外部就可以正常执行。

2.2.3 事务隔离行为

事务隔离级别类似于教室A和教室B之间的那道墙,隔离级别越高表示墙体越厚。隔音效果越好。
数据库中读取数据存在的三大问题:(三大读问题)
● 脏读:读取到没有提交到数据库的数据,叫做脏读。
● 不可重复读:在同一个事务当中,第一次和第二次读取的数据不一样。
● 幻读:读到的数据是假的。
事务隔离级别包括四个级别:
● 读未提交:READ_UNCOMMITTED
○ 这种隔离级别,存在脏读问题,所谓的脏读(dirty read)表示能够读取到其它事务未提交的数据。
● 读提交:READ_COMMITTED
○ 解决了脏读问题,其它事务提交之后才能读到,但存在不可重复读问题。
● 可重复读:REPEATABLE_READ
○ 解决了不可重复读,可以达到可重复读效果,只要当前事务不结束,读取到的数据一直都是一样的。但存在幻读问题。
● 序列化:SERIALIZABLE
○ 解决了幻读问题,事务排队执行。不支持并发。
大家可以通过一个表格来记忆:
在这里插入图片描述

在Spring代码中如何设置隔离级别?
隔离级别在spring中以枚举类型存在:
在这里插入图片描述
比如在类上或方法上加

@Transactional(isolation = Isolation.READ_COMMITTED)
2.2.3.1 测试

测试事务隔离级别:
怎么测试:一个service负责插入,一个service负责查询。负责插入的service要模拟延迟。
负责查询的类

package com.cky.service.impl;

import com.cky.Dao.AccountDao;
import com.cky.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service("i1")
public class isolataionService1 {
    @Resource(name = "accountDao")
    private AccountDao accountDao;
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public void query(){
        Account account = accountDao.selectByActno("act0030");
        System.out.println(account);

    }

}

负责插入的类 并且有延迟

package com.cky.service.impl;

import com.cky.Dao.AccountDao;
import com.cky.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service("i2")
public class isolataionService2 {
    @Resource(name = "accountDao")
    private AccountDao accountDao;
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public void insert(){
        accountDao.insert(new Account("act0030",2000.0));
        try {
            Thread.sleep(1000*20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.2.3.2 读未提交

我们首先设置读未提交
就是可以读到还没有提交到数据库中缓存中的信息

  @Test
    public void testisolation(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        isolataionService1 i1 = applicationContext.getBean("i1", isolataionService1.class);
        i1.query();
    }
    @Test
    public void testisolation1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        isolataionService2 i2 = applicationContext.getBean("i2", isolataionService2.class);
        i2.insert();
    }

先执行testisolation1 在执行testisolation。
我们可以看到 数据表中还没有内容,但是我们可以读取到
在这里插入图片描述

2.2.3.3 读提交

设置读提交
还是上边的程序,我们可以看到并查询不到内容,因为还没有保存在数据库里
在这里插入图片描述

2.2.3.4 可重复读

设置可重复读
这里用来查询 前后延迟五秒查询 且在这五秒内 更新数据库内容,看查询内容是否一致。

package com.cky.service.impl;

import com.cky.Dao.AccountDao;
import com.cky.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service("i1")
public class isolataionService1 {
    @Resource(name = "accountDao")
    private AccountDao accountDao;
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    public void query(){
        Account account = accountDao.selectByActno("act0040");
        System.out.println(account);
        try {
            Thread.sleep(1000*5);
        } catch (InterruptedException e) {
        }
        Account account1 = accountDao.selectByActno("act0040");
        System.out.println(account1);
    }

}

用来更新

package com.cky.service.impl;

import com.cky.Dao.AccountDao;
import com.cky.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service("i2")
public class isolataionService2 {
    @Resource(name = "accountDao")
    private AccountDao accountDao;
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public void insert(){
        accountDao.insert(new Account("act0040",2000.0));
    }
    public void update(){
        accountDao.update(new Account("act0040",6000.0));}
}

测试 在类上点击test 一起测试

package com.cky.test;


import com.cky.service.AccountService;
import com.cky.service.UserService;
import com.cky.service.impl.isolataionService1;
import com.cky.service.impl.isolataionService2;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {

    @Test
    public void testisolation(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        isolataionService1 i1 = applicationContext.getBean("i1", isolataionService1.class);
        i1.query();
    }
    @Test
    public void testisolation1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        isolataionService2 i2 = applicationContext.getBean("i2", isolataionService2.class);
        i2.update();
    }
}

在这里插入图片描述

可以看到读取的内容一致。更新并没有造成影响。

2.2.4 事务超时

@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);
}

2.2.5 只读事务

@Transactional(readOnly = true)

将当前事务设置为只读事务,在该事务执行过程中只允许select语句执行,delete insert update均不可执行。
该特性的作用是:启动spring的优化策略。提高select语句执行效率。
如果该事务中确实没有增删改操作,建议设置为只读事务。

2.2.6 设置哪些异常回滚事务

@Transactional(rollbackFor = RuntimeException.class)

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

2.2.7 设置哪些异常不回滚事务

@Transactional(noRollbackFor = NullPointerException.class)

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

2.3 事务全注解开发

一个配置类来代替sprin.xml文件

package com.powernode.bank;

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;

@Configuration  //配置类
@ComponentScan("com.powernode.bank") //扫描包
@EnableTransactionManagement //事务驱动
public class Spring6Config {

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

    @Bean(name = "jdbcTemplate")
    //spring会执行该方法,之后从spring容器中自动进行匹配
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    @Bean
    public DataSourceTransactionManager 
        //spring会执行该方法,之后从spring容器中自动进行匹配getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}


网站公告

今日签到

点亮在社区的每一天
去签到