Spring-事务学习

spring事务

1. 什么是事务?

事务其实是一个并发控制单位,是用户定义的一个操作序列,这些操作要么全部完成,要不全部不完成,是一个不可分割的工作单位。事务有 ACID 四个特性,即:

在这里插入图片描述

  1. 原子性(Atomicity):事务中的所有操作,或者全部完成,或者全部不完成,是一个不可分割的工作单元。
  2. 一致性(Consistency):在事务开始之前和事务结束以后,数据库的完整性没有被破坏。
  3. 隔离性(Isolation):多个事务之间是独立的,不相互影响的。

​ 数据库允许多个并发事务同时对数据进行读写和修改, 隔离性可以防止多个事务并发执行时由于交叉执行而导致的数据的不一致。事物分为不同的隔离级别。

  • 读未提交
  • 读已提交
  • 可重复读(数据库的默认的事物隔离级别)
  • 串行化
  1. 持久性(Durability):事务处理结束后,对数据的修改就是永久的,即便系统故障也不会丢失。

为了解释清楚这个问题,我们举个简单的例子:银行里树哥要给小黑转 1000 块钱,这时候会有两个必要的操作:

  1. 将树哥的账户余额减少 1000 元。
  2. 将小黑的账户余额增加 1000 元。

这两个操作,要么一起都完成,要么都不完成。如果其中某个成功,另外一个失败,那么就会出现严重的问题。而我们要保证这个操作的原子性,就必须通过 Spring 事务来完成,这就是 Spring 事务存在的原因。

如果你深入了解过 MySQL 事务,那么你应该知道:MySQL 默认情况下,对于所有的单条语句都作为一个单独的事务来执行。我们要使用 MySQL 事务的时候,可以通过手动提交事务来控制事务范围。Spring 事务的本质,其实就是通过 Spring AOP 切面技术,在合适的地方开启事务,接着在合适的地方提交事务或回滚事务,从而实现了业务编程层面的事务操作。

2. spring 事物的三大基础设施

1. PlatformTransactionManager 事务管理器接口

package org.springframework.transaction;import org.springframework.lang.Nullable;public interface PlatformTransactionManager extends TransactionManager {// 获取事务TransactionStatus getTransaction(@Nullable TransactionDefinition definition)throws TransactionException;// 提交事务void commit(TransactionStatus status) throws TransactionException;// 事务回滚void rollback(TransactionStatus status) throws TransactionException;}

2. TransactionDefinition 定义事务的属性

package org.springframework.transaction;import org.springframework.lang.Nullable;public interface TransactionDefinition {int PROPAGATION_REQUIRED = 0;int PROPAGATION_SUPPORTS = 1;int PROPAGATION_MANDATORY = 2;int PROPAGATION_REQUIRES_NEW = 3;int PROPAGATION_NOT_SUPPORTED = 4;int PROPAGATION_NEVER = 5;int PROPAGATION_NESTED = 6;int ISOLATION_DEFAULT = -1;int ISOLATION_READ_UNCOMMITTED = 1;  // same as java.sql.Connection.TRANSACTION_READ_UNCOMMITTED;int ISOLATION_READ_COMMITTED = 2;  // same as java.sql.Connection.TRANSACTION_READ_COMMITTED;int ISOLATION_REPEATABLE_READ = 4;  // same as java.sql.Connection.TRANSACTION_REPEATABLE_READ;int ISOLATION_SERIALIZABLE = 8;  // same as java.sql.Connection.TRANSACTION_SERIALIZABLE;/*** Use the default timeout of the underlying transaction system,* or none if timeouts are not supported.*/int TIMEOUT_DEFAULT = -1;/*** Return the propagation behavior.*/default int getPropagationBehavior() {return PROPAGATION_REQUIRED;}/*** Return the isolation level.*/default int getIsolationLevel() {return ISOLATION_DEFAULT;}/*** Return the transaction timeout.* @return the transaction timeout*/default int getTimeout() {return TIMEOUT_DEFAULT;}/*** Return whether to optimize as a read-only transaction.*/default boolean isReadOnly() {return false;}/*** Return the name of this transaction. Can be {@code null}.* <p>This will be used as the transaction name to be shown in a* transaction monitor, if applicable (for example, WebLogic's).* <p>In case of Spring's declarative transactions, the exposed name will be* the {@code fully-qualified class name + "." + method name} (by default).* @return the name of this transaction ({@code null} by default}* @see org.springframework.transaction.interceptor.TransactionAspectSupport* @see org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionName()*/@Nullabledefault String getName() {return null;}static TransactionDefinition withDefaults() {return StaticTransactionDefinition.INSTANCE;}
}

3. TransactionStatus Spring事务 或者 Spring事务的状态

package org.springframework.transaction;import java.io.Flushable;public interface TransactionStatus extends TransactionExecution, SavepointManager, Flushable {/*** Return whether this transaction internally carries a savepoint,* that is, has been created as nested transaction based on a savepoint.* <p>This method is mainly here for diagnostic purposes, alongside* {@link #isNewTransaction()}. For programmatic handling of custom* savepoints, use the operations provided by {@link SavepointManager}.* @see #isNewTransaction()* @see #createSavepoint()* @see #rollbackToSavepoint(Object)* @see #releaseSavepoint(Object)*/boolean hasSavepoint();/*** Flush the underlying session to the datastore, if applicable:* for example, all affected Hibernate/JPA sessions.* <p>This is effectively just a hint and may be a no-op if the underlying* transaction manager does not have a flush concept. A flush signal may* get applied to the primary resource or to transaction synchronizations,* depending on the underlying resource.*/@Overridevoid flush();boolean isNewTransaction();/*** Set the transaction rollback-only. This instructs the transaction manager* that the only possible outcome of the transaction may be a rollback, as* alternative to throwing an exception which would in turn trigger a rollback.*/void setRollbackOnly();/*** Return whether the transaction has been marked as rollback-only* (either by the application or by the transaction infrastructure).*/boolean isRollbackOnly();/*** Return whether this transaction is completed, that is,* whether it has already been committed or rolled back.*/boolean isCompleted();
}

3. Spring 事务-编程式事务

问题: 代码耦合度较高

package com.example.sqldemo.spring_transaction;import com.example.sqldemo.mapper.SqlMapper;
import com.example.sqldemo.pojo.AuditModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;import javax.annotation.Resource;@Component
public class SpringTransactionTest {@Resourceprivate SqlMapper sqlMapper;/*** jdbc 的 数据库的一个连接的template ,用于执行各种的sql语句*/@Autowiredprivate JdbcTemplate jdbcTemplate;/*** 事务管理器*/@Autowiredprivate PlatformTransactionManager transactionManager;/*** Spring的一个封装过的事物template: 可以设置事务的隔离级别和事务的传播行为*/@Autowiredprivate TransactionTemplate transactionTemplate;// 需要自己进行事物的提交和回滚public  void test1(String[] args) {// 1. 定义默认的事物属性DefaultTransactionDefinition definition = new DefaultTransactionDefinition();// 2. 获取事务TransactionStatus status = transactionManager.getTransaction(definition);try {// 3. 执行sqljdbcTemplate.update("update user set money = ? where username = ?",100,"李四");// 提交事务transactionManager.commit(status);} catch (DataAccessException | TransactionException e) {e.printStackTrace();// 事务回滚transactionManager.rollback(status);}}// 使用 Spring封装的事物的template, 帮助你进行事物的提交和回滚public  void test2() {transactionTemplate.execute(new TransactionCallbackWithoutResult() {@Overrideprotected void doInTransactionWithoutResult(TransactionStatus status) {// 执行sqlAuditModel auditModel = new AuditModel();auditModel.setId(1232313232);auditModel.setCountry("西班牙");auditModel.setUser("哈哈哈哈");sqlMapper.insert(auditModel);}});}
}

我们点进去这个execute() 方法, 可以看到 这个Spring的这个TransactionTemplate 它其实帮你做了这个提交和回滚的部分, 不需要自己来做这部分的逻辑. 很方便.

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/61013.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

CVE-2024-2961漏洞的简单学习

简单介绍 PHP利用glibc iconv()中的一个缓冲区溢出漏洞&#xff0c;实现将文件读取提升为任意命令执行漏洞 在php读取文件的时候可以使用 php://filter伪协议利用 iconv 函数, 从而可以利用该漏洞进行 RCE 漏洞的利用场景 PHP的所有标准文件读取操作都受到了影响&#xff1…

[Kotlin标准函数] run、with、apply、also、let、use等

文章目录 1. let2. with2.1 参数解析2.2 用法示例 3、use函数 1. let 2. with 2.1 参数解析 第一个参数可以是一个任意类型的对象&#xff0c; 第二个参数是一个Lambda表达式 with函数会在Lambda表达式中提供第一个参数对象的上下文&#xff0c; 并使用Lambda表达式中的最后…

2024山西省网络建设运维第十八届职业院校技能大赛解析答案(3. ansible 服务)

\3. ansible 服务 任务描述:请采用ansible,实现自动化运维。 (1)在Server2上安装系统自带的ansible-core,作为ansible 控制节 点。Linux1-linux7 作为 ansible 的受控节点。 (2)编写/root/resolv.yml 剧本,实现在所有linux主机的 /etc/resolv.conf文件,文件内容均…

PageOffice打开保存文件的执行流程(工作原理)

一、PageOffice打开文件 触发PageOffiice弹窗&#xff1a;在想要打开Office文件的页面上&#xff0c;通过点击按钮或链接来调用POBrowser.openWindow() 方法&#xff0c;此时会弹出一个PageOffice浏览器窗口&#xff0c;这个窗口中会自动加载openWindow()方法的第一个参数指向…

【FFmpeg系列】:音频处理

前言 在多媒体处理领域&#xff0c;FFmpeg无疑是一个不可或缺的利器。它功能强大且高度灵活&#xff0c;能够轻松应对各种音频和视频处理任务&#xff0c;无论是简单的格式转换&#xff0c;还是复杂的音频编辑&#xff0c;都不在话下。然而&#xff0c;要想真正发挥FFmpeg的潜…

段探测的研究

在介绍今天的内容之前&#xff0c;我们先要知道一些前置的知识 跳过繁琐的介绍&#xff0c;我们单刀直入&#xff0c;介绍一个划时代的CPU 8086 8086 从8086开始&#xff0c;CPU扩展到了16位&#xff0c;地址的位宽扩展到了20位&#xff0c;自此之后我们现在所熟知的计算机结…

pytorch环境问题以及探索Dataloader的数据格式

1 问题 DataLoader object is not subscriptable No module named matplotlib/torchvision.io 2 方法 针对问题一&#xff1a;“dataloader” object is not subscriptable 是一个 Python 中常见的错误。它通常是由于对 dataloader 取下标而导致的。 在 PyTorch 中&#xff0c;…

Linux:进程的优先级 进程切换

文章目录 前言一、进程优先级1.1 基本概念1.2 查看系统进程1.3 PRI和NI1.4 调整优先级1.4.1 top命令1.4.2 nice命令1.4.3 renice命令 二、进程切换2.1 补充概念2.2 进程的运行和切换步骤&#xff08;重要&#xff09; 二、Linux2.6内核进程O(1)调度队列&#xff08;重要&#x…

【学习心得】算力云平台上的大模型部署并实现远程调用

以AutoDL算力云平台为例&#xff0c;部署国产开源ChatGLM3b模型。 一、准备工作 &#xff08;1&#xff09;准备一台算力服务器 首先&#xff0c;进入AutoDL官网的算力时长选择算力服务器资源。 创建好后会自动跳转控制台的“容器实例”界面&#xff0c;稍等片刻后选择“快捷…

【Linux】—进程地址空间

大家好呀&#xff0c;我是残念&#xff0c;希望在你看完之后&#xff0c;能对你有所帮助&#xff0c;有什么不足请指正&#xff01;共同学习交流哦 本文由&#xff1a;残念ing原创CSDN首发&#xff0c;如需要转载请通知 个人主页&#xff1a;残念ing-CSDN博客&#xff0c;欢迎各…

leetcode-44-通配符匹配

题解&#xff1a; 代码&#xff1a; 参考&#xff1a; (1)牛客华为机试HJ71字符串通配符 (2)leetcode-10-正则表达式匹配

【redis】redis

1.linux离线安装 解压 redis-6.2.6.tar.gz进入redis-6.2.6执行make编译执行./make install PREFIX/app/soft/redis6安装 2. 使用客户端 redis-cli 启动默认6379 redis-cli -p port指定端口 -h ip -n 仓库号 【redis-cli -p 6379 -h 192.168.23.22】 auth username#passwd 或…

低成本出租屋5G CPE解决方案:ZX7981PG/ZX7981PM WIFI6千兆高速网络

刚搬进新租的房子&#xff0c;没有网络&#xff0c;开个热点&#xff1f;续航不太行。随身WIFI&#xff1f;大多是百兆级网络。找人拉宽带&#xff1f;太麻烦&#xff0c;退租的时候也不能带着走。5G CPE倒是个不错的选择&#xff0c;插入SIM卡就能直接连接5G网络&#xff0c;千…

学习日记_20241117_聚类方法(高斯混合模型)

前言 提醒&#xff1a; 文章内容为方便作者自己后日复习与查阅而进行的书写与发布&#xff0c;其中引用内容都会使用链接表明出处&#xff08;如有侵权问题&#xff0c;请及时联系&#xff09;。 其中内容多为一次书写&#xff0c;缺少检查与订正&#xff0c;如有问题或其他拓展…

列出D3的所有交互方法,并给出示例

D3.js 提供了丰富的交互方法&#xff0c;可以用来增强图表的用户交互体验。以下是一些常用的交互方法及其示例&#xff1a; 1. 鼠标事件 on("mouseover", function) 用途: 当鼠标悬停在元素上时触发。示例:svg.selectAll(".bar").on("mouseover&qu…

设计模式-参考的雷丰阳老师直播课

一般开发中使用的模式为模版模式策略模式组合&#xff0c;模版用来定义骨架&#xff0c;策略用来实现细节。 模版模式 策略模式 与模版模式特别像&#xff0c;模版模式会定义好步骤定义好框架&#xff0c;策略模式定义小细节 入口类 使用模版模式策略模式开发支付 以上使用…

基于BERT的情感分析

基于BERT的情感分析 1. 项目背景 情感分析&#xff08;Sentiment Analysis&#xff09;是自然语言处理的重要应用之一&#xff0c;用于判断文本的情感倾向&#xff0c;如正面、负面或中性。随着深度学习的发展&#xff0c;预训练语言模型如BERT在各种自然语言处理任务中取得了…

37.超级简易的计算器 C语言

超级简单&#xff0c;简单到甚至这个计算器输入都比较反人类 但是足够简单 有输入功能有Switch语句支持四种运算还能检查除数是不是0还能打印出完整的式子 #define _CRT_SECURE_NO_WARNINGS// 禁用安全警告 #include <stdio.h>int main() {double num1, num2;// 声明两…

【tokenization分词】WordPiece, Byte-Pair Encoding(BPE), Byte-level BPE(BBPE)的原理和代码

目录 前言 1、word (词粒度) 2、char (字符粒度) 3、subword (子词粒度) WordPiece Byte-Pair Encoding (BPE) Byte-level BPE(BBPE) 总结 前言 Tokenization&#xff08;分词&#xff09; 在自然语言处理(NLP)的任务中是最基本的一步&#xff0c;将文本处理成一串tok…

深入解析 MySQL 数据库:数据库时区问题

在 MySQL 数据库中&#xff0c;时区管理是一个重要且复杂的主题&#xff0c;尤其是在全球化的应用程序中。以下是关于 MySQL 数据库时区问题的深入解析&#xff1a; 1. 时区的概念 时区是指地球表面被分为若干个区域&#xff0c;每个区域的标准时间相对协调世界时 (UTC) 有所…