当前位置: 首页 > news >正文

spring事务处理

系列文章目录

Spring中事务的处理相关内容的学习


文章目录

  • 系列文章目录
  • 前言
  • 一、Spring事务简介
  • 二、案例:银行账户转账
    • 1.题目要求和思路分析
    • 2.实现步骤
    • 3.实现结构
  • 三、spring事务角色
  • 四、spring事务相关配置
  • 五、案例:转账业务追加日志
    • 1.题目要求和思路分析
    • 2.解决方案和代码实现
  • 总结


前言


一、Spring事务简介

在这里插入图片描述

二、案例:银行账户转账

1.题目要求和思路分析

在这里插入图片描述

2.实现步骤

在这里插入图片描述

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

3.实现结构

项目结构
在这里插入图片描述

JdbcConfig

package org.example.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;import javax.sql.DataSource;public class JdbcConfig {@Value("${jdbc.driver}")private String drive;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource(){DruidDataSource ds=new DruidDataSource();ds.setDriverClassName(drive);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}//配置事务管理器@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();transactionManager.setDataSource(dataSource);return transactionManager;}
}

MybatisConfig

package org.example.config;import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MybatisConfig {//定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean ssfb=new SqlSessionFactoryBean();ssfb.setTypeAliasesPackage("org.example.domain");ssfb.setDataSource(dataSource);return ssfb;}//定义bean,返回MapperScannerConfigurer对象@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc=new MapperScannerConfigurer();msc.setBasePackage("org.example.dao");return msc;}
}

SpringConfig

package org.example.config;import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}

AccountDao

package org.example.dao;import org.apache.ibatis.annotations.*;
import org.example.domain.Account;import java.util.List;public interface AccountDao {@Update("update tbl_account set money = money + #{money} where name = #{name}")void inMoney(@Param("name") String name, @Param("money") Double money);@Update("update tbl_account set money = money - #{money} where name = #{name}")void outMoney(@Param("name") String name, @Param("money") Double money);
}

Account

package org.example.domain;public class Account {private Integer id;private String name;private Double money;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}

AccountService

package org.example.service;import org.springframework.transaction.annotation.Transactional;public interface AccountService {/*** 转账操作* @param out 转出方* @param in 转入方* @param money 金额*///开启事务@Transactionalpublic void transfer(String out,String in,Double money);
}

AccountServiceImpl

package org.example.service.impl;import org.example.dao.AccountDao;
import org.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;public void transfer(String out, String in, Double money) {accountDao.outMoney(out,money);int i=10/0;accountDao.inMoney(in,money);}
}

AccountServiceTest

package org.example.service;import org.example.config.SpringConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;//设定类运行器
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void testTransfer() throws Exception{accountService.transfer("Tom","Jerry",100.0);}
}

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=****

三、spring事务角色

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

四、spring事务相关配置

在这里插入图片描述

有些异常是默认不参加回滚的。只有运行时异常和Error的错误spring会自动回滚,其他异常是不参加回滚,所以要设置事务回滚异常

五、案例:转账业务追加日志

1.题目要求和思路分析

在这里插入图片描述

2.解决方案和代码实现

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

项目结构
在这里插入图片描述
LogDao

package org.example.dao;import org.apache.ibatis.annotations.Insert;public interface LogDao {@Insert("insert into tbl_log (info,createDate) values(#{info},now()) ")void log(String info);
}

LogService

package org.example.service;import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;public interface LogService {@Transactional(propagation = Propagation.REQUIRES_NEW)void log(String out,String in,Double money);
}

LogServiceImpl

package org.example.service.impl;import org.example.dao.LogDao;
import org.example.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class LogServiceImpl implements LogService {@Autowiredprivate LogDao logDao;public void log(String out, String in, Double money) {logDao.log("转账操作由"+out+"到"+in+",金额:"+money);}
}

AccountServiceImpl

package org.example.service.impl;import org.example.dao.AccountDao;
import org.example.service.AccountService;
import org.example.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Autowiredprivate LogService logService;public void transfer(String out, String in, Double money) {try {accountDao.outMoney(out,money);accountDao.inMoney(in,money);}finally {logService.log(out,in,money);}}
}

其余代码按照上面银行转账的操作进行编写,须注意数据库要新建tbl_log的表。


总结

本节主要讲了spring中对于事务的处理,并分析事务管理的一些小案例
参考视频

相关文章:

spring事务处理

系列文章目录 Spring中事务的处理相关内容的学习 文章目录系列文章目录前言一、Spring事务简介二、案例:银行账户转账1.题目要求和思路分析2.实现步骤3.实现结构三、spring事务角色四、spring事务相关配置五、案例:转账业务追加日志1.题目要求和思路分析…...

2023 年博客之星的入围规则

目的 感谢各位博主和社区的大力支持,我们的博客之星活动成为了 IT界非常知名的博主荣誉的象征,博主在这个过程中也给大家贡献了很多优质内容。 在过去的几年中,博主们给我们博客之星活动提了很多建议,其中最强烈的一点就是&#…...

【新2023Q2押题JAVA】华为OD机试 - 查找树中的元素 or 查找二叉树节点

最近更新的博客 华为od 2023 | 什么是华为od,od 薪资待遇,od机试题清单华为OD机试真题大全,用 Python 解华为机试题 | 机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为od机试,独家整理 已参加机试人员的实战技巧本篇题解:查找树中的元素 or 查找二叉树…...

MySQL 日志:undo log、redo log、binlog 有什么用?

目录一、bin log1.作用2.刷盘时机3.日志格式二、redo log1.为什么需要redo log2.基本概念3.作用3.刷盘时机三、undo log1.作用四、Mysql的时机顺序五、redo log 与 binlog 的两阶段提交六、总结一、bin log 1.作用 MySQL的bin log日志是用来记录MySQL中增删改时的记录日志。 …...

ETL 与 ELT的关键区别

ETL 和 ELT 之间的主要区别在于数据转换发生的时间和地点 — 这些变化可能看起来很小,但会产生很大的影响! ETL 和 ELT 是数据团队引入、转换并最终向利益干系人公开数据的两种主要方式。它们是与现代云数据仓库和 ETL 工具的开发并行发展的流程。 在任…...

Thinkphp 6.0模版的杂项和表单令牌

本节课我们来学习一下模版的杂项和表单令牌的功能。 一.模版的杂项 1. 有时,我们需要输出类似模版标签或语法的数据,这时会被模版解析; 2. 此时,我们就使用模版的原样输出标签{literal}; {literal} 变量标…...

linux常问

查看当前进程 ps -l 列出与本次登录有关的进程信息; ps -aux 查询内存中进程信息; ps -aux | grep * 查询 *进程的详细信息; top 查看内存中进程的动态信息; kill -9 pid 杀死进程。...

ToBeWritten之物联网MQTT、Z-Wave等协议

也许每个人出生的时候都以为这世界都是为他一个人而存在的,当他发现自己错的时候,他便开始长大 少走了弯路,也就错过了风景,无论如何,感谢经历 转移发布平台通知:将不再在CSDN博客发布新文章,敬…...

C# 行为型模式之责任链模式

责任链模式:请求从链中的一个对象传递到下一个对象,直到请求被响应为止。通过这种方式在对象之间去除耦合。 用途:请假审批、采购审批等。 案例介绍:以公司采购东西为例子来实现责任链模式。公司规定,采购架构总价在…...

layui实现请求前添加一个加载 loading 的效果,并在请求成功后关闭

1.使用 layui 的 layer 组件来实现请求前添加一个加载 loading 的效果,并在请求成功后关闭。 $("#switch").click(function() {layer.confirm(确认切换至英文环境?, function(index) {var loadingIndex layer.load(1, {shade: [0.1,#fff] //0.1透明度的…...

iostat / sar 命令详解

作用 iostat主要用于监控系统设备的IO负载情况&#xff0c;根据这个可以看出当前系统的写入量和读取量&#xff0c;CPU负载和磁盘负载。 iostat属于sysstat软件包。可以用yum install sysstat 直接安装。 iostat用法 1.用法&#xff1a;iostat [选项] [<时间间隔>] […...

2023-04-06:拥抱Golang,优化FFmpeg音频编码器,探究encode_audio.c的内部结构。

2023-04-06&#xff1a;拥抱Golang&#xff0c;优化FFmpeg音频编码器&#xff0c;探究encode_audio.c的内部结构。 答案2023-04-06&#xff1a; 见moonfdd/ffmpeg-go库。 这段代码是一个示例程序&#xff0c;用于将音频 PCM 数据编码为 MP2 格式的音频文件。下面是代码的详细…...

归排、计排深度理解

归并排序&#xff1a;是创建在归并操作上的一种有效的排序算法。算法是采用分治法&#xff08;Divide and Conquer&#xff09;的一个非常典型的应用&#xff0c;且各层分治递归可以同时进行。归并排序思路简单&#xff0c;速度仅次于快速排序&#xff0c;为稳定排序算法&#…...

设计原则(单一职责原则 开放封闭原则 里氏替换原则 依赖倒置原则 接口隔离原则 迪米特法则)

设计原则单一职责原则(SRP)从三大特性角度看原则:应用的设计模式&#xff1a;开放封闭原则(OCP)从三大特性角度看原则:应用的设计模式&#xff1a;里氏替换原则(LSP)从三大特性角度看原则:应用的设计模式&#xff1a;依赖倒置原则(DIP)从三大特性角度看原则:应用的设计模式&…...

好像模拟了一个引力场

( A, B )---3*30*2---( 1, 0 )( 0, 1 ) 做一个网络让输入只有3个节点&#xff0c;每个训练集里有4张图片&#xff0c;让B的训练集全为0&#xff0c;排列组合A&#xff0c;观察迭代次数平均值的变化。 A-B 迭代次数 0 1 0 2*0*0*7-0*0*0*0 12957.31 0 0 0 2*0*0*7-0*0…...

MySQL优化——Explain分析执行计划详解

文章目录前言一. 查看SQL执行频率二. 定位低效率执行SQL三. explain分析执行计划3.1 id3.2 select_type3.3 table3.4 type3.5 key3.6 rows3.7 extra四. show profile分析SQL前言 在应用的的开发过程中&#xff0c;由于初期数据量小&#xff0c;开发人员写 SQL 语句时更重视功能…...

xcode 14.3 file not found libarclite_iphoneos.a

最近升级到xcode 14.3 版本的同学&#xff0c;会遇到这个一个问题 File not found: /Users/johnson/Downloads/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_iphoneos.a 解决方法(亲测有效) 在podfile文件中&#xff0c;增…...

基于AI+数据驱动的慢查询索引推荐

目前&#xff0c;美团内部每天产生的慢查询数量已经超过上亿条。如何高效准确地为慢查询推荐缺失的索引来改善其执行性能&#xff0c;是美团数据库研发中心面临的一项挑战。为此&#xff0c;我们与华东师范大学开展了科研合作&#xff0c;在AI领域对索引推荐进行了探索和实践&a…...

【ESP32】嵌入式FreeRtos--Task

FreeRTOS中文数据手册&#xff1a;https://www.freertos.org/zh-cn-cmn-s/RTOS.html 任务函数 任务函数描述xTaskCreate()使用动态的方法创建一个任务xTaskCreateStatic()使用静态的方法创建一个任务xTaskCreatePinnedToCore指定任务运行的核心(最后一个参数)vTaskDelete()删…...

【操作系统】面试官都爱问的进程调度算法

【操作系统】面试官都爱问的进程调度算法 文章目录【操作系统】面试官都爱问的进程调度算法先来先服务调度算法最短作业优先调度算法高响应比优先调度算法时间片轮转调度算法最高优先级调度算法多级反馈队列调度算法进程调度算法也称 CPU 调度算法&#xff0c;毕竟进程是由 CPU…...

Spring-Web spi机制解析

org.springframework.web.SpringServletContainerInitializer#onStartup 在这里打个断点&#xff0c;查看程序是否会进来 可以发现程序进来了&#xff1a;主要spi机制&#xff0c;看看这里做了什么操作&#xff1f; 去寻找所有实现了WebApplicationInitializer的类 将符合条件…...

数据结构|将链表中小于0的数全部放在大于0的数的前面

题1&#xff1a; 某带头结点的非空单链表L中所有元素为整数&#xff0c;结点类型定义如下&#xff1a; typedef struct node { int data; struct node *next; } LinkNode; 设计一个尽可能高效的算法&#xff0c;将所有小于零的结点移到所有大于等于零的结点的前面。 分…...

分享106个ASP影音娱乐源码,总有一款适合您

分享106个ASP影音娱乐源码&#xff0c;总有一款适合您 106个ASP影音娱乐源码下载链接&#xff1a;https://pan.baidu.com/s/13k8UaJrCci_z4Q0gQbtDtg?pwdjq44 提取码&#xff1a;jq44 Python采集代码下载链接&#xff1a;采集代码.zip - 蓝奏云 我的博客地址&#xff1a;亚…...

win10 PyCharm Anaconda过程记录

1、Anaconda用来配置不同的虚拟环境 进入 Anaconda Prompt 输入conda activate Hui&#xff08;此为自己创建的放置虚拟环境的文件夹&#xff09; 编译运行过程中出现No module named seaborn后 pip install seaborn...

Chrome扩展程序导出备份与本地导入浏览器

现在即使在国内下载个chrome&#xff0c;转个插件也千难万难。现在科学上网也越来越难&#xff0c;由于众所周知的原因&#xff0c;连qiang这个话题都是敏感词。哀默于心死&#xff0c;还是回避这个话题 只要把之前装的chrome打包&#xff0c;然后再重新安装一遍。操作步骤如下…...

mysql常用运算符

mysql常用运算符一、去重和空值1.distinct2.null参与运算3.用ifnull函数解决问题二、比较运算符三、dual伪表和数值运算1.常规运算2.比较运算符3.<>安全相等四、常用正则相关的比较运算符1.基本运算符2.模糊查询3.正则表达式五、逻辑运算符六、位运算总结一、去重和空值 …...

PyTorch 深度学习框架:优雅而简洁的代码实现

PyTorch 是由 Facebook 发布的深度学习框架&#xff0c;旨在为研究人员和工程师提供快速、灵活和简单的实验平台。与其他框架相比&#xff0c;PyTorch 具有简洁的 API 和灵活的动态计算图&#xff0c;使得构建和训练深度神经网络变得更加优雅和简洁。本文将介绍 PyTorch 的基本…...

【SpringMVC】请求重定向和转发

forward&#xff1a;表示转发 处理器方法返回ModelAndView,实现转发forward 语法&#xff1a; setViewName("forward:视图文件完整路径") forward特点&#xff1a; 不和视图解析器一同使用&#xff0c;就当项目中没有视图解析器redirect&#xff1a;表示重定向 处理…...

Vue中@click的常见修饰符

在 Vue 的click事件中&#xff0c;可以使用以下修饰符&#xff1a; .stop&#xff1a;阻止事件继续传播。.prevent&#xff1a;阻止默认事件。.capture&#xff1a;使用事件捕获模式。.self&#xff1a;只当事件是从侦听器绑定的元素本身触发时才触发回调。.once&#xff1a;只…...

软件测试面试复盘:技术面没有难倒我,hr面被虐的体无完肤

一般提到面试&#xff0c;肯定都会想问一下面试结果&#xff0c;我就大概的说一下面试结果&#xff0c;哈哈&#xff0c;其实不太想说&#xff0c;因为挺惨的&#xff0c;并没有像很多大佬一样 ”已拿字节阿里腾讯各大厂offer”&#xff0c;但是毕竟是自己的经历&#xff0c;无…...