1.事务概述
*什么是事务
在一个业务流程中,通常要多条DML(insert delete update )语句共同联合才能完成,这多条DML语句必须同时成功,或者同时失败,这样才能保证数据的安全。
多条DML要么同时成功,要么同时失败,这叫做事务。
事务:Transaction(tx)
事务的四个处理步骤:
第一步:开启事务(start transaction)
第二步:执行核心业务代码
第三步:提交事务(如果核心业务处理过程中没有出现异常)(commit transaction)
第四步:回滚事务(如果核心业务处理过程中出现异常)(rollback transaction)
事务的四个特性:
a原子性:事务是最小的工作单元,不可再分。
c一致性:事务要求要么同时成功,要么同时失败。事务前和事务后的总量不变。
i隔离性:事务和事务之间因为有隔离性,才可以保证互不干扰。
d持久性:持久性是事务结束的标志。
2.引入事务场景
以银行账户转账为例学习事务。两个账户act-001和act-002. act-001账户向act-002账户转账1000块钱,必须同时成功,或者同时失败。(一个减成功,一个加成功。这两条update语句必须同时成功,或同时失败。=======你仔细想,若一个转账1000成功,没了1000,但是对方没接收到,也就是转1000出去,但钱不见了。。。那就麻烦了)
连接数据库的技术采用spring框架的JdbcTemplate。
采用三层架构搭建:
模块名:spring6-013-tx-bank
依赖:
<dependencies> <!--spring context依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.0.0-M2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!-- spring-jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>6.0.0-M2</version> </dependency> <!-- mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency> <!-- 德鲁伊连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.13</version> </dependency> <!-- @Resource注解--> <dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> <version>2.1.1</version> </dependency> </dependencies>
第一步:准备数据库表
表结构:
表数据:
第二步:创建包结构
第三步:准备POJO类
package com.bank.pojo; //银行账户类 public class Account { private String actno; private Double balance; public Account(){ } @Override public String toString() { return "Account{" + "actno='" + actno + '\'' + ", balance=" + balance + '}'; } public Account(String actno, Double balance) { this.actno = actno; this.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 com.bank.dao; //专门负责账户信息的CRUD操作 //DAO中只执行SQL语句,没有任何业务逻辑。。。也就是说DAO不和业务挂钩 import com.bank.pojo.Account; public interface AccountDao { // 根据账号查询信息 Account selectByActno(String actno); // 更新账户信息 int update(Account act); }
第五步:编写业务层??
package com.bank.dao.impl; import com.bank.dao.AccountDao; import com.bank.pojo.Account; import jakarta.annotation.Resource; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository("accountDao") public class AccountDaoImpl implements AccountDao { @Resource(name = "jdbcTemplate") private JdbcTemplate jdbcTemplate; @Override public Account selectByActno(String actno) { String sql = "select actno, balance from t_act where actno = ?"; Account account = jdbcTemplate.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 = jdbcTemplate.update(sql, act.getBalance(), act.getActno()); return count; } }
package com.bank.service; //业务接口 //事务就是在这个接口下控制的 public interface AccountService { // 转账业务方法 void transfer(String fromActno, String toActno,double money);//转出账户,转入账户,金额 }package com.bank.service.impl; import com.bank.dao.AccountDao; import com.bank.pojo.Account; import com.bank.service.AccountService; import jakarta.annotation.Resource; import org.springframework.stereotype.Service; @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); // 模拟异常 String s = null; s.toString(); 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="com.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/spring"/> <property name="username" value="root"/> <property name="password" value="lg654321"/> </bean> <!-- 配置JdbcTemplate--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
第七步:编写表示层(测试程序)
public class SpringTXTest { @Test public void testSPTX(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); AccountService accountService = applicationContext.getBean("accountService", AccountService.class); try{ accountService.transfer("act-001","act-002",10000); System.out.println("转账成功"); }catch (Exception e){ e.printStackTrace(); } } }
3.spring对事务的支持
3.1spring实现事务的两种方式:
*编程式事务
通过编写代码的方式来实现事务的管理
*声明式事务
基于注释方式(使用得较多---重点)
基于XML配置方式
3.2spring事务管理API(API-----应用编程接口)
spring对事务的管理 底层实现方式是基于AOP实现的。采用AOP的方式进行了封装。
所以spring专门针对事务开发了一套API,API的核心接口如下:
PlatformTransactionManager接口:spring事务管理器的核心接口。在spring6中它有两个实现: *DataSourceTransactionManager: 支持JdbcTemplate,MyBaits,Hibernate等事务管理 *JdbcTransactionManager:支持分布式事务管理 如果在spring6中要使用JdbcTemplate,就要使用DataSourceTransactionManager来管理事务。(spring内置已经写好了,可以直接用)
3.3事务之注解方式:
编写配置文件
<?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"> <!-- 组件扫描--> <context:component-scan base-package="com.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/spring"/> <property name="username" value="root"/> <property name="password" value="lg654321"/> </bean> <!-- 配置JdbcTemplate--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置事务管理器--> <bean id="txManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--开始事务注解驱动器。(开启事务注解)告诉spring框架,采用注解的方式去控制事务--> <tx:annotation-driven transaction-manager="txManger"/> </beans>组件扫描是肯定要的,不然你怎么用注解开发
数据源也肯定需要的,因为配置事务管理器时需要用到,
事务注解驱动器也肯定要,这样才能开始注解的事务
jdbcTemplate就不懂,只知道删掉它会出错,无法执行。
开启事务?
@Service("accountService")
@Transactional
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);
// 模拟异常
// String s = null;
// s.toString();
count += accountDao.update(toAct);
if (count!=2){
throw new RuntimeException("转账失败,联系银行");
}
//*第三步:如果执行业务流程过程中,没有异常。--提交事务
//*第四步:如果执行业务流程过程中,出现异常,--回滚事务
}
}
只需在原先之前写的代码基础上, 加一句注解:@Transactional 就搞定了。
3.4事务的传播行为
public @interface Transactional { @AliasFor("transactionManager") String value() default ""; @AliasFor("value") String transactionManager() default ""; Propagation propagation() default Propagation.REQUIRED;//事务的传播行为 Isolation isolation() default Isolation.DEFAULT; //隔离级别 int timeout() default -1; //事务的超时时间 String timeoutString() default ""; boolean readOnly() default false; Class<? extends Throwable>[] rollbackFor() default {}; //出现哪些异常时,回滚事务 String[] rollbackForClassName() default {}; Class<? extends Throwable>[] noRollbackFor() default {}; //出现哪些异常时,不回滚事务 String[] noRollbackForClassName() default {};事务中的重点属性:事务传播行为;事务隔离级别;事务超时;只读事务;设置出现哪些异常回滚事务;设置出现哪些异常不回滚事务
事务传播行为
什么是事务的传播行为?
在service类中有a()方法 和 b() 方法,a()方法上有事务,b()方法上也有事务,当a()方法执行过程中 调用b()方法, 事务是如何传递的?? 合并到一个事务里? 还是开启一个新的事务? 这就是事务的传播行为。
事务传播行为在spring框架中被定义为枚举类型:
共七种传播行为:
REQUIRED:支持当前事务,如果不存在就新建一个(默认)【没有就新建,有就用原来的】
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式进行【有就加入,没就不管了】
MANDATORY:必须运行在一个事务中,如果当前没有事务正在发生,将抛出一个异常【有就加入,没有就抛异常】
REQUIRES_NEW:开启一个新的事务,如果一个事务已经存在,则将这个存在的事务挂起【不管有没有,直接开启一个新事务,开启的新事务和旧事务不存在嵌套关系,旧事务被挂起】
NOT_SUPPORTED:以非事务方式运行,如果有事务存在,挂起当前事务【不支持事务,存在就挂起】
NEVER:以非事务方式运行,如果有事务存在, 则抛出异常【不支持事务,存在就抛异常】
NESTED:如果当前正有一个事务在进行中,则该方法应当运行在一个嵌套式事务中。被嵌套的事务可以独立于外层事务进行提交或回滚。如果外层事务不存在,行为就像REQUIRED一样
【有事务的话,就在这个事务里再嵌套一个完全独立的事务,嵌套的事务可以独立的提交和回滚。没有事务就和REQUIRED一样】
在代码中设置事务的传播行为:
@Transactional(propagation = Propagation.REQUIRED)
3.5事务隔离级别
事务隔离级别类似于教室A和教室B之间的那道墙,隔离级别越高表示墙体越厚,隔音效果越好。
数据库中读取数据存在三大问题:(三大读问题)
*脏读:读取到没有提交到数据库的数据,叫脏读(读到缓存里的数据)
*不可重复读:在同一个事务当中,第一次和第二次读取的数据结果不一样
*幻读:读到的数据是假的
事务隔离级别包括四个级别:
*读未提交:READ_UNCOMMITTED(当前事务可以 读到别的事务没有提交的数据)
该隔离级别,存在脏读问题,所谓脏读表示能够读取到其他事务未提交的数据。
*读提交:READ_COMMITTED(对方事务提交之后的数据我才能读到)
解决了脏读问题,其他事务提交之后才能读到,但存在 不可重复读问题。
*可重复读:REPEATABLE_READ
解决了不可重复读,达到可重复读效果,只要当前事务不结束,读取到的数据一直都是一样的。但存在幻读问题
*序列化:SERIALIZABLE
解决了幻读问题,事务排队执行。不支持并发。(只要事务并发,就一定存在幻读。)
3.6事务超时
代码如下:
@Transactional(timeout = 10)
以上代码表示设置事务 的超时时间为 10秒。
表示事务执行超过10秒后,若该事务中所有DML语句还没有执行完毕的话,最终结果会选择回滚
默认值为-1,表示没有时间限制
这里有个坑,事务的超时时间指的是哪段时间?
在当前事务当中,最后一条DML语句执行之前的时间。如果最后一条DML语句后面有很多业务逻辑,这些业务代码执行的时间不被计入超时时间。
3.7只读事务
代码如下:
@Transactional(readOnly = true)
将当前事务设为只读事务,在该事务执行过程中只允许select语句执行,delete insert update均不可执行。
该特性的作用是:启动spring的优化策略。提高select语句执行效率。
如果该事务中确实没有增删改操作,建议设置为只读事务。
3.8设置哪些异常回滚事务
代码如下:
@Transactional(rollbackFor = RuntimeException.class)
表示只有发生runtimeException 异常 或 该异常的子类异常 才回滚
3.9设置哪些异常不回滚事务
代码如下:
@Transactional(noRollbackFor = RuntimeException.class)
表示发生RuntimeException 或 该异常的子类异常 时 不回滚,其他异常则回滚。
回不回滚事务 的 区别 是 发生异常后,是否 撤销 之前的 增删改操作。
3.10全注解式开发事务
关键代码:
@Configuration //代替spring.xml配置文件,在这个类中完成配置 @ComponentScan("com.bank")//组件扫描 @EnableTransactionManagement//开启事务注解 public class Spring6Config { //spring框架,看到@Bean注解后,会调用这个被标志的方法,这个方法的返回值是一个Java对象,该对象会自动纳入IoC容器管理 //返回的对象就是spring容器当中的一个Bean了 //并且这个bean的id 是 dataSource @Bean("dataSource") public DruidDataSource getDataSource(){ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc.mysql://localhost:3306/spring"); dataSource.setUsername("root"); dataSource.setPassword("lg654321"); return dataSource; } @Bean("jdbcTemplate") public JdbcTemplate getjdbcTemplate(DataSource dataSource){//spring在调用该方法时,会自动传递一个dataSource对象过来 JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDataSource(dataSource); return jdbcTemplate; } @Bean("txManger") public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){ DataSourceTransactionManager txManger = new DataSourceTransactionManager(); txManger.setDataSource(dataSource); return txManger; }
测试代码
@Test public void testNOxml(){ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Config.class); AccountService accountService = applicationContext.getBean("accountService", AccountService.class); try{ accountService.transfer("act-001","act-002",10000); System.out.println("转账成功"); }catch (Exception e){ e.printStackTrace(); } }
3.11声明式事务之XML实现方式
配置步骤:
*第一步:配置事务管理器
*第二步:配置通知
*第三步:配置切面
需添加aspectj依赖