> 文章列表 > 【SSM】Spring6(十一.Spring对事务支持)

【SSM】Spring6(十一.Spring对事务支持)

【SSM】Spring6(十一.Spring对事务支持)

文章目录

  • 1.引入事务场景
    • 1.1准备数据库
    • 1.2 创建包结构
    • 1.3 创建POJO类
    • 1.4 编写持久层
    • 1.5 编写业务层
    • 1.6 Spring配置文件
    • 1.7 表示层(测试)
    • 1.8 模拟异常
  • 2.Spring对事务的支持
    • 2.1 spring事务管理API
    • 2.2 spring事务之注解方式
    • 2.3 事务的属性
    • 2.4 事务的传播行为
    • 2.5 事务隔离级别
    • 2.6 事务超时
    • 2.7 只读事务
    • 2.8 设置哪些异常回滚
    • 2.9 设置哪些异常不回滚
    • 2.10 事务的全注解式开发
    • 2.11 声明式事务之XML

1.引入事务场景

引入依赖

<?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>com.sdnu</groupId><artifactId>spring-013-tx-bank</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><!--仓库--><repositories><!--spring里程碑版本的仓库--><repository><id>repository.spring.milestone</id><name>Spring Milestone Repository</name><url>https://repo.spring.io/milestone</url></repository></repositories><!--依赖--><dependencies><!--spring context--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.0-M2</version></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>5.1.37</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><!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency></dependencies><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties></project>

1.1准备数据库

表结构:
【SSM】Spring6(十一.Spring对事务支持)
数据:
【SSM】Spring6(十一.Spring对事务支持)

1.2 创建包结构

【SSM】Spring6(十一.Spring对事务支持)

1.3 创建POJO类

package com.sdnu.bank.pojo;public class Account {private String actno;private Double balance;public Account() {}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;}@Overridepublic String toString() {return "Account{" +"actno='" + actno + '\\'' +", balance=" + balance +'}';}
}

1.4 编写持久层

package com.sdnu.bank.dao;import com.sdnu.bank.pojo.Account;/*** 专门负责账户信息的CRUD*/
public interface AccountDao {/*** 根据账号查询账户信息* @param actno 账号* @return 账户*/Account selectByActno(String actno);/*** 更新账户信息* @param act 账户* @return 更新的结果*/int update(Account act);
}
package com.sdnu.bank.dao.impl;import com.sdnu.bank.dao.AccountDao;
import com.sdnu.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;@Overridepublic 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;}@Overridepublic int update(Account act) {String sql = "update t_act set balance = ? where actno = ?";int count = jdbcTemplate.update(sql, act.getBalance(), act.getActno());return count;}
}

1.5 编写业务层

package com.sdnu.bank.service;/*** 业务接口* 事务就是在这个接口下控制的*/
public interface AccountService {/*** 转账业务* @param fromActno 转出账号* @param toActno 转入账号* @param money 转出金额*/void transfer(String fromActno, String toActno, double money);
}
package com.sdnu.bank.service.impl;import com.sdnu.bank.dao.AccountDao;
import com.sdnu.bank.pojo.Account;
import com.sdnu.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;@Overridepublic 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("转账失败");}}
}

1.6 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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!--组件扫描--><context:component-scan base-package="com.sdnu.bank"/><!--配置数据源--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/spring6"/><property name="username" value="root"/><property name="password" value="Wgf720130601"/></bean><!--配置jdbcTemplate--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean></beans>

1.7 表示层(测试)

package com.sdnu.spring6.test;import com.sdnu.bank.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTXTest {@Testpublic void testSpringTx(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");AccountService accountService = applicationContext.getBean("accountService", AccountService.class);try{accountService.transfer("act001", "act002", 5000);System.out.println("转账成功");}catch (Exception e){e.printStackTrace();}}
}

【SSM】Spring6(十一.Spring对事务支持)
【SSM】Spring6(十一.Spring对事务支持)

1.8 模拟异常

【SSM】Spring6(十一.Spring对事务支持)
在AccountServiceImpl中加入异常(模拟异常),运行。

【SSM】Spring6(十一.Spring对事务支持)
我们发现少了5000元。

2.Spring对事务的支持

【SSM】Spring6(十一.Spring对事务支持)

2.1 spring事务管理API

【SSM】Spring6(十一.Spring对事务支持)
PlatformTransactionManager接口:spring事务管理器的核心接口。在Spring6中它有两个实现:
● DataSourceTransactionManager:支持JdbcTemplate、MyBatis、Hibernate等事务管理。
● JtaTransactionManager:支持分布式事务管理。
如果要在Spring6中使用JdbcTemplate,就要使用DataSourceTransactionManager来管理事务。(Spring内置写好了,可以直接用。)

2.2 spring事务之注解方式

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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!--组件扫描--><context:component-scan base-package="com.sdnu.bank"/><!--配置数据源--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/spring6"/><property name="username" value="root"/><property name="password" value="Wgf720130601"/></bean><!--配置jdbcTemplate--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean><!--配置事务管理器--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--开启事务注解驱动器,开启事务注解,告诉spring采用注解的方式去控制事务--><tx:annotation-driven transaction-manager="txManager"/></beans>

【SSM】Spring6(十一.Spring对事务支持)
在类上添加该注解,该类中所有的方法都有事务。在某个方法上添加该注解,表示只有这个方法使用事务。

加了事务控制后,虽然出现了异常,但是钱没有少。

【SSM】Spring6(十一.Spring对事务支持)

2.3 事务的属性

事务的属性主要有以下几个:
● 事务传播行为
● 事务隔离级别
● 事务超时
● 只读事务
● 设置出现哪些异常回滚事务
● 设置出现哪些异常不回滚事务

2.4 事务的传播行为

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

● REQUIRED:支持当前事务,如果不存在就新建一个(默认)【没有就新建,有就加入】
● SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行【有就加入,没有就不管了】
● MANDATORY:必须运行在一个事务中,如果当前没有事务正在发生,将抛出一个异常【有就加入,没有就抛异常】
● REQUIRES_NEW:开启一个新的事务,如果一个事务已经存在,则将这个存在的事务挂起【不管有没有,直接开启一个新事务,开启的新事务和之前的事务不存在嵌套关系,之前事务被挂起】
● NOT_SUPPORTED:以非事务方式运行,如果有事务存在,挂起当前事务【不支持事务,存在就挂起】
● NEVER:以非事务方式运行,如果有事务存在,抛出异常【不支持事务,存在就抛异常】
● NESTED:如果当前正有一个事务在进行中,则该方法应当运行在一个嵌套式事务中。被嵌套的事务可以独立于外层事务进行提交或回滚。如果外层事务不存在,行为就像REQUIRED一样。【有事务的话,就在这个事务里再嵌套一个完全独立的事务,嵌套的事务可以独立的提交和回滚。没有事务就和REQUIRED一样。】

设置

@Transactional(propagation = Propagation.REQUIRED)

2.5 事务隔离级别

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

2.6 事务超时

@Transactional(timeout = 10)

表示超过10秒如果该事务中所有的DML语句还没有执行完毕的话,最终结果会选择回滚。
默认值-1,表示没有时间限制。
(注意:在当前事务当中,最后一条DML语句执行之前的时间。如果最后一条DML语句后面很有很多业务逻辑,这些业务代码执行的时间不被计入超时时间。)

2.7 只读事务

启动spring的优化策略。提高select语句执行效率。

2.8 设置哪些异常回滚

@Transactional(rollbackFor = RuntimeException.class)

2.9 设置哪些异常不回滚

@Transactional(noRollbackFor = NullPointerException.class)

2.10 事务的全注解式开发

package com.sdnu.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 //代替spring配置文件,在这个类当中完成配置
@ComponentScan("com.sdnu.bank") //组件扫描
@EnableTransactionManagement //开启事务注解
public class Spring6Config {//Spring容器看到@Bean注解后,会调用被标注的这个方法,这个方法的返回值是一个Java对象,这个Java对象会纳入Spring容器管理//返回的对象就是Spring容器当中的一个Bean,并且这个Bean的名字是dataSource@Bean("dataSource")public DruidDataSource getDataSource(){DruidDataSource druidDataSource = new DruidDataSource();druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring6");druidDataSource.setUsername("root");druidDataSource.setPassword("123456");return druidDataSource;}@Bean("jdbcTemplate")//spring容器在调用这个方法的时候会自动给我们传递过来一个dataSource对象public JdbcTemplate getJdbcTemplate(DataSource dataSource){JdbcTemplate jdbcTemplate = new JdbcTemplate();jdbcTemplate.setDataSource(dataSource);return jdbcTemplate;}@Bean("txManager")public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){DataSourceTransactionManager txManager = new DataSourceTransactionManager();txManager.setDataSource(dataSource);return txManager;}
}

2.11 声明式事务之XML