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

uniapp 对接腾讯云IM群组成员管理(增删改查)

UniApp 实战&#xff1a;腾讯云IM群组成员管理&#xff08;增删改查&#xff09; 一、前言 在社交类App开发中&#xff0c;群组成员管理是核心功能之一。本文将基于UniApp框架&#xff0c;结合腾讯云IM SDK&#xff0c;详细讲解如何实现群组成员的增删改查全流程。 权限校验…...

深入剖析AI大模型:大模型时代的 Prompt 工程全解析

今天聊的内容&#xff0c;我认为是AI开发里面非常重要的内容。它在AI开发里无处不在&#xff0c;当你对 AI 助手说 "用李白的风格写一首关于人工智能的诗"&#xff0c;或者让翻译模型 "将这段合同翻译成商务日语" 时&#xff0c;输入的这句话就是 Prompt。…...

如何在看板中体现优先级变化

在看板中有效体现优先级变化的关键措施包括&#xff1a;采用颜色或标签标识优先级、设置任务排序规则、使用独立的优先级列或泳道、结合自动化规则同步优先级变化、建立定期的优先级审查流程。其中&#xff0c;设置任务排序规则尤其重要&#xff0c;因为它让看板视觉上直观地体…...

Spring Boot面试题精选汇总

&#x1f91f;致敬读者 &#x1f7e9;感谢阅读&#x1f7e6;笑口常开&#x1f7ea;生日快乐⬛早点睡觉 &#x1f4d8;博主相关 &#x1f7e7;博主信息&#x1f7e8;博客首页&#x1f7eb;专栏推荐&#x1f7e5;活动信息 文章目录 Spring Boot面试题精选汇总⚙️ **一、核心概…...

【服务器压力测试】本地PC电脑作为服务器运行时出现卡顿和资源紧张(Windows/Linux)

要让本地PC电脑作为服务器运行时出现卡顿和资源紧张的情况&#xff0c;可以通过以下几种方式模拟或触发&#xff1a; 1. 增加CPU负载 运行大量计算密集型任务&#xff0c;例如&#xff1a; 使用多线程循环执行复杂计算&#xff08;如数学运算、加密解密等&#xff09;。运行图…...

【JavaSE】绘图与事件入门学习笔记

-Java绘图坐标体系 坐标体系-介绍 坐标原点位于左上角&#xff0c;以像素为单位。 在Java坐标系中,第一个是x坐标,表示当前位置为水平方向&#xff0c;距离坐标原点x个像素;第二个是y坐标&#xff0c;表示当前位置为垂直方向&#xff0c;距离坐标原点y个像素。 坐标体系-像素 …...

【论文阅读28】-CNN-BiLSTM-Attention-(2024)

本文把滑坡位移序列拆开、筛优质因子&#xff0c;再用 CNN-BiLSTM-Attention 来动态预测每个子序列&#xff0c;最后重构出总位移&#xff0c;预测效果超越传统模型。 文章目录 1 引言2 方法2.1 位移时间序列加性模型2.2 变分模态分解 (VMD) 具体步骤2.3.1 样本熵&#xff08;S…...

Mac下Android Studio扫描根目录卡死问题记录

环境信息 操作系统: macOS 15.5 (Apple M2芯片)Android Studio版本: Meerkat Feature Drop | 2024.3.2 Patch 1 (Build #AI-243.26053.27.2432.13536105, 2025年5月22日构建) 问题现象 在项目开发过程中&#xff0c;提示一个依赖外部头文件的cpp源文件需要同步&#xff0c;点…...

rnn判断string中第一次出现a的下标

# coding:utf8 import torch import torch.nn as nn import numpy as np import random import json""" 基于pytorch的网络编写 实现一个RNN网络完成多分类任务 判断字符 a 第一次出现在字符串中的位置 """class TorchModel(nn.Module):def __in…...

Xen Server服务器释放磁盘空间

disk.sh #!/bin/bashcd /run/sr-mount/e54f0646-ae11-0457-b64f-eba4673b824c # 全部虚拟机物理磁盘文件存储 a$(ls -l | awk {print $NF} | cut -d. -f1) # 使用中的虚拟机物理磁盘文件 b$(xe vm-disk-list --multiple | grep uuid | awk {print $NF})printf "%s\n"…...