当前位置: 首页 > 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…...

AI-调查研究-01-正念冥想有用吗?对健康的影响及科学指南

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; &#x1f680; AI篇持续更新中&#xff01;&#xff08;长期更新&#xff09; 目前2025年06月05日更新到&#xff1a; AI炼丹日志-28 - Aud…...

Leetcode 3576. Transform Array to All Equal Elements

Leetcode 3576. Transform Array to All Equal Elements 1. 解题思路2. 代码实现 题目链接&#xff1a;3576. Transform Array to All Equal Elements 1. 解题思路 这一题思路上就是分别考察一下是否能将其转化为全1或者全-1数组即可。 至于每一种情况是否可以达到&#xf…...

【2025年】解决Burpsuite抓不到https包的问题

环境&#xff1a;windows11 burpsuite:2025.5 在抓取https网站时&#xff0c;burpsuite抓取不到https数据包&#xff0c;只显示&#xff1a; 解决该问题只需如下三个步骤&#xff1a; 1、浏览器中访问 http://burp 2、下载 CA certificate 证书 3、在设置--隐私与安全--…...

IoT/HCIP实验-3/LiteOS操作系统内核实验(任务、内存、信号量、CMSIS..)

文章目录 概述HelloWorld 工程C/C配置编译器主配置Makefile脚本烧录器主配置运行结果程序调用栈 任务管理实验实验结果osal 系统适配层osal_task_create 其他实验实验源码内存管理实验互斥锁实验信号量实验 CMISIS接口实验还是得JlINKCMSIS 简介LiteOS->CMSIS任务间消息交互…...

代理篇12|深入理解 Vite中的Proxy接口代理配置

在前端开发中,常常会遇到 跨域请求接口 的情况。为了解决这个问题,Vite 和 Webpack 都提供了 proxy 代理功能,用于将本地开发请求转发到后端服务器。 什么是代理(proxy)? 代理是在开发过程中,前端项目通过开发服务器,将指定的请求“转发”到真实的后端服务器,从而绕…...

docker 部署发现spring.profiles.active 问题

报错&#xff1a; org.springframework.boot.context.config.InvalidConfigDataPropertyException: Property spring.profiles.active imported from location class path resource [application-test.yml] is invalid in a profile specific resource [origin: class path re…...

HashMap中的put方法执行流程(流程图)

1 put操作整体流程 HashMap 的 put 操作是其最核心的功能之一。在 JDK 1.8 及以后版本中&#xff0c;其主要逻辑封装在 putVal 这个内部方法中。整个过程大致如下&#xff1a; 初始判断与哈希计算&#xff1a; 首先&#xff0c;putVal 方法会检查当前的 table&#xff08;也就…...

云原生安全实战:API网关Kong的鉴权与限流详解

&#x1f525;「炎码工坊」技术弹药已装填&#xff01; 点击关注 → 解锁工业级干货【工具实测|项目避坑|源码燃烧指南】 一、基础概念 1. API网关&#xff08;API Gateway&#xff09; API网关是微服务架构中的核心组件&#xff0c;负责统一管理所有API的流量入口。它像一座…...

【JVM面试篇】高频八股汇总——类加载和类加载器

目录 1. 讲一下类加载过程&#xff1f; 2. Java创建对象的过程&#xff1f; 3. 对象的生命周期&#xff1f; 4. 类加载器有哪些&#xff1f; 5. 双亲委派模型的作用&#xff08;好处&#xff09;&#xff1f; 6. 讲一下类的加载和双亲委派原则&#xff1f; 7. 双亲委派模…...

LangChain 中的文档加载器(Loader)与文本切分器(Splitter)详解《二》

&#x1f9e0; LangChain 中 TextSplitter 的使用详解&#xff1a;从基础到进阶&#xff08;附代码&#xff09; 一、前言 在处理大规模文本数据时&#xff0c;特别是在构建知识库或进行大模型训练与推理时&#xff0c;文本切分&#xff08;Text Splitting&#xff09; 是一个…...