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

news/2025/2/21 5:49:05/

文章目录

  • 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准备数据库

表结构:
在这里插入图片描述
数据:
在这里插入图片描述

1.2 创建包结构

在这里插入图片描述

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

在这里插入图片描述
在这里插入图片描述

1.8 模拟异常

在这里插入图片描述
在AccountServiceImpl中加入异常(模拟异常),运行。

在这里插入图片描述
我们发现少了5000元。

2.Spring对事务的支持

在这里插入图片描述

2.1 spring事务管理API

在这里插入图片描述
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>

在这里插入图片描述
在类上添加该注解,该类中所有的方法都有事务。在某个方法上添加该注解,表示只有这个方法使用事务。

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

在这里插入图片描述

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


http://www.ppmy.cn/news/42547.html

相关文章

Linux -- 基础IO

文章目录1. 基础认识2. 回顾C文件接口2.1 现象一2.2 现象二2.3 fprintf()函数回顾2.4 fnprintf()函数使用2.5 "a"模式3. 系统接口3.1 open()和close()3.2 write()3.3 read()3.4 C文件接口和系统接口关系3.5 文件描述符3.6 深度理解Linux下一切皆文件3.7 FILE是什么3.…

SwiftUI_属性装饰器

关键词ObservableObject / PublishedEnvironmentObjectStateBindingEnvironmentObservableObject / Published ObservedObject 的用处和 State 非常相似&#xff0c;从名字看来它是来修饰一个对象的&#xff0c;这个对象可以给多个独立的 View 使用。如果你用 ObservedObject …

Centos 服务器放行TCP、UDP端口教程

Centos 服务器放行TCP、UDP端口教程1、telnet2、nc3、firewall1&#xff09;放行TCP端口2&#xff09;放行UDP端口3&#xff09;放行端口范围8888-99994&#xff09;关闭某个端口5&#xff09;查看已经放行的端口6&#xff09;查看防火墙状态7&#xff09;开启防火墙8&#xff…

棒球市场拓展计划·棒球联盟

几十年来&#xff0c;棒球一直是一项流行的运动&#xff0c;无论是在美国还是在世界各地。然而&#xff0c;尽管它很受欢迎&#xff0c;但棒球市场基本上保持静止&#xff0c;新进入者很少&#xff0c;增长机会有限。为了扩大棒球市场&#xff0c;有必要制定新的战略和方法来吸…

Spring5学习笔记01

一、课程介绍 Spring是什么呢&#xff1f; 它是一个轻量级的、开源的JavaEE框架&#xff0c;它的出现是为了解决企业繁琐的开发包括复杂代码&#xff0c;它可以用很优雅、很简洁的方式进行实现&#xff0c;也就是说它为了简化企业开发而生&#xff0c;而它在目前的企业中应用…

肖 sir_就业课__007项目讲解

项目讲解 一、银行项目 信贷业务 理财业务 卡系统&#xff08;信用卡&#xff09; 二、电商项目 三、保险项目 保险参考链接&#xff1a; 前端 1、https://www.picc.com/ 中国人民保险 2、http://www.cpic.com.cn/ 太平洋保险 3、https://www.gwcslife.com/ 长生人寿保险公…

类和对象深入讲解(1)

目录 1.类和对象的初步认识 1.1面向过程和面向对象的区别 1.2类的引入 1.3内的定义 1.4类的访问限定符及封装 1.4.1访问限定符 1.4.2 封装 1.5类的作用域 1.6类对象模型 1.6.1如何计算类对象大小 1.类和对象的初步认识 1.1面向过程和面向对象的区别 C语言是面向过程的…

JUC之CountDownLatch与CyclicBarrier

1.前言 在java.util.concurrent包中为我们提供了很多的线程同步工具类&#xff0c;例如CountDownLatch与CyclicBarrier&#xff0c;那么它们主要的用途是什么呢&#xff1f;且看后续分析。 2.CountDownLatch 2.1 什么是CountDownLatch CountDownLatch&#xff0c;顾名思义&…