Spring对事务的实现

Spring对事务的支持

  • 事务概述
    • 事务的四个处理过程
    • 事务的四个特性
  • 引入事务场景
  • Spring实现事务的两种方式
    • 声明式事务之注解实现方式

事务概述

  • 在一个业务流程当中,通常需要多条DML(insert delete update)语句共同联合才能完成,这多条DML语句必须同时成功,或者同时失败,这样才能保证数据的安全。
  • 多条DML要么同时成功,要么同时失败,这叫做事务。

事务的四个处理过程

第一步:开启事务 (start transaction)
第二步:执行核心业务代码
第三步:提交事务(如果核心业务处理过程中没有出现异常)
第四步:回滚事务(如果核心业务处理过程中出现异常)

事务的四个特性

原子性:事务是最小的工作单元,不可再分。
一致性:事务要求要么同时成功,要么同时失败。事务前和事务后的总量不变。
隔离性:事务和事务之间因为有隔离性,才可以保证互不干扰。
持久性:持久性是事务结束的标志。

引入事务场景

例:两个账户act-001和act-002。act-001账户向act-002账户转账10000,必须同时成功,或者同时失败。

新建模块:spring6-jdbc

连接数据库的技术采用Spring框架的JdbcTemplate

pom.xml

<?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.w</groupId>
    <artifactId>spring6-jdbc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>repository.spring.milestone</id>
            <name>Spring Milestone Repository</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.0-M2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--新增的依赖:mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
        <!--新增的依赖:spring jdbc,这个依赖中有JdbcTemplate-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.0-M2</version>
        </dependency>

<!--@Resource注解-->
        <dependency>
            <groupId>jakarta.annotation</groupId>
            <artifactId>jakarta.annotation-api</artifactId>
            <version>2.1.1</version>
        </dependency>
        
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

</project>

第一步:准备数据库表
t_act
表结构
在这里插入图片描述
表数据
在这里插入图片描述
第二步:创建包结构
com.w.spring6.bank.pojo
com.w.spring6.bank.service
com.w.spring6.bank.service.impl
com.w.spring6.bank.dao
com.w.spring6.bank.dao.impl

第三步:准备POJO类
Account.java

package com.w.spring6.bank.pojo;

public class Account {
    private String actno;
    private Double balance;

    @Override
    public String toString() {
        return "Account{" +
                "actno='" + actno + '\'' +
                ", balance=" + 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;
    }
}

第四步:编写持久层
AccountDao接口

package com.w.spring6.bank.dao;

import com.w.spring6.bank.pojo.Account;

public interface AccountDao {

    /**
     * 根据账号查询余额
     * @param actno
     * @return
     */
    Account selectByActno(String actno);

    /**
     * 更新账户
     * @param act
     * @return
     */
    int update(Account act);

}


AccountDaoImpl.java

package com.w.spring6.bank.dao.impl;

import com.w.spring6.bank.dao.AccountDao;
import com.w.spring6.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;

    @Override
    public 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;
    }

    @Override
    public int update(Account act) {
        String sql = "update t_act set balance = ? where actno = ?";
        int count = jdbcTemplate.update(sql, act.getBalance(), act.getActno());
        return count;
    }
}

第五步:编写业务层
AccountService接口

package com.w.spring6.bank.service;

public interface AccountService {

    /**
     * 转账
     * @param fromActno
     * @param toActno
     * @param money
     */
    void transfer(String fromActno, String toActno, double money);
}

AccountServiceImpl.java

package com.w.spring6.bank.service.impl;

import com.w.spring6.bank.dao.AccountDao;
import com.w.spring6.bank.pojo.Account;
import com.w.spring6.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;

    @Override
    public 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("转账失败,请联系银行");
        }
    }
}


第六步:编写Spring配置文件
Spring-bank.xml

<?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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.w.spring6.bank"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3307/idea-spring-test"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

第七步:编写表示层(测试程序)
BankTest.java

package com.w.spring6.test;

import com.w.spring6.bank.service.AccountService;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BankTest {
    @Test
    public void testTransfer(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        try {
            accountService.transfer("act-001", "act-002", 10000);
            System.out.println("转账成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

运行结果:
在这里插入图片描述
在这里插入图片描述

模拟异常:
在这里插入图片描述
卧槽,少了10000
在这里插入图片描述

Spring实现事务的两种方式

  • 编程式事务:通过编写代码的方式来实现事务的管理。
  • 声明式事务:基于注解方式,基于XML配置方式

声明式事务之注解实现方式

第一步:在spring配置文件中配置事务管理器。
spring-bank.xml

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"/>
</bean>

第二步:在spring配置文件中引入tx命名空间,在spring配置文件中配置“事务注解驱动器”,开始注解的方式控制事务。
<tx:annotation-driven transaction-manager=“transactionManager”/>

第三步:在service类上或方法上添加@Transactional注解
@Transactional
public class AccountServiceImpl implements AccountService {
}

接着继续运行测试
发现没有丢钱啦!
在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

RT-Thread STM32F407 PWM

为了展示PWM效果&#xff0c;这里用ADC来采集PWM输出通道的电平变化 第一步&#xff0c;进入RT-Thread Settings配置PWM驱动 第二步&#xff0c;进入board.h&#xff0c;打开PWM宏 第三步&#xff0c;进入STM32CubeMX&#xff0c;配置时钟及PWM 第四步&#xff0c;回到R…

鸿蒙4.0开发笔记之DevEco Studio如何使用Previewer窗口预览器(一)

一、预览器作用 DevEco Studio预览器概况在HarmonyOS应用开发过程中&#xff0c;通过使用预览器&#xff0c;可以查看应用的UI效果&#xff0c;方便开发者实时查看应用的运行效果&#xff0c;随时调整代码。 二、打开Previewer预览器 1、正常启动 打开预览器的位置在DevEco…

三十分钟学会zookeeper

zookeeper 一、前提知识 集群与分布式 ​ 集群&#xff1a;将一个任务部署在多个服务器&#xff0c;每个服务器都能独立完成该任务。 ​ 分布式&#xff1a;将一个任务拆分成若干个子任务&#xff0c;由若干个服务器分别完成这些子任务&#xff0c;每个服务器只能完成某个特…

有趣的按钮分享

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站。 广告打完&#xff0c;我们进入正题&#xff0c;先看效果&#xff1a; 废话不多&#xff0c;上源码&#xff1a; <button class&quo…

【STM32】RTC(实时时钟)

1.RTC简介 本质&#xff1a;计数器 RTC中断是外部中断&#xff08;EXTI&#xff09; 当VDD掉电的时候&#xff0c;Vbat可以通过电源--->实时计时 STM32的RTC外设&#xff08;Real Time Clock&#xff09;&#xff0c;实质是一个 掉电 后还继续运行的定时器。从定时器的角度…

C#,数值计算——插值和外推,双线性插值(Bilin_interp)的计算方法与源程序

1 文本格式 using System; namespace Legalsoft.Truffer { /// <summary> /// 双线性插值 /// interpolation routines for two dimensions /// Object for bilinear interpolation on a matrix. /// Construct with a vector of x1. /// value…

How to import dgl-cu113 如何导入 dgl-cu113

参考这个 从How to import dgl-cu113 如何导入 dgl-cu113https://discuss.dgl.ai/t/how-to-import-dgl-cu113/3381https://discuss.dgl.ai/t/how-to-import-dgl-cu113/3381

Pycharm之配置python虚拟环境

最近给身边的人写了脚本&#xff0c;在自己电脑可以正常运行。分享给我身边的人&#xff0c;却运行不起来&#xff0c;然后把报错的截图给我看了&#xff0c;所以难道不会利用pycharm搭建虚拟的环境&#xff1f;记录一下配置的过程。 第一步&#xff1a;右键要打开的python的代…

Idea 创建 Spring 项目(保姆级)

描述信息 最近卷起来&#xff0c;系统学习Spring&#xff1b;俗话说&#xff1a;万事开头难&#xff1b;创建一个Spring项目在网上找了好久没有找到好的方式&#xff1b;摸索了半天产出如下文档。 在 Idea 中新建项目 填写信息如下 生成项目目录结构 pom添加依赖 <depende…

华夏ERP打包手册

Maven安装及环境配置 1.下载 浏览器搜索maven点击apache Maven 2.选择安装目录&#xff0c;注意不能有中文 3.环境变量配置 点击计算机右键属性>高级系统设置>环境变量 新建系统变量 MAVEN_HOME 变量值是安装目录 进入path点击新建点击编辑&#xff0c;写入% MAVEN_H…

Leetcode刷题详解——不同路径

1. 题目链接&#xff1a;62. 不同路径 2. 题目描述&#xff1a; 一个机器人位于一个 m x n 网格的左上角 &#xff08;起始点在下图中标记为 “Start” &#xff09;。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角&#xff08;在下图中标记为 “Finish”…

40 _ 初识动态规划:如何巧妙解决“双十一”购物时的凑单问题?

淘宝的“双十一”购物节有各种促销活动,比如“满200元减50元”。假设你女朋友的购物车中有n个(n>100)想买的商品,她希望从里面选几个,在凑够满减条件的前提下,让选出来的商品价格总和最大程度地接近满减条件(200元),这样就可以极大限度地“薅羊毛”。作为程序员的你…

零代码编程:用ChatGPT自动合并多个Word文件

一个文件夹中有多个docx格式的word文档&#xff1a; 想要把它们都合并成一个文件&#xff0c;然后打印&#xff0c;可以在ChatGPT中输入提示词&#xff1a; 你是一个Python编程专家&#xff0c;要完成一个处理word内容的任务&#xff0c;具体步骤如下&#xff1a; 打开文件夹…

WPF 使用.ttf文件中的图标失败

本章讲述问题&#xff1a;WPF 使用.ttf文件中的图标失败&#xff0c;变成白框问题。 在WPF开发过程中&#xff0c;我们需要使用.ttf文件中的图标和文字&#xff0c;但是经常会遇到类似问题&#xff1a;WPF 在XMAL里增加图标字体时没办法实时显示出来只显示一个小方框&#xff0…

DAY57 739. 每日温度 + 496.下一个更大元素 I

739. 每日温度 题目要求&#xff1a; 请根据每日 气温 列表&#xff0c;重新生成一个列表。对应位置的输出为&#xff1a;要想观测到更高的气温&#xff0c;至少需要等待的天数。如果气温在这之后都不会升高&#xff0c;请在该位置用 0 来代替。 例如&#xff0c;给定一个列…

PVP2 ProVideoPlayer 2.1.6(PVP2多屏幕演示投放软件)

PVP2 ProVideoPlayer2是一款视频播放和管理软件&#xff0c;旨在帮助用户实现多屏幕视频播放和内容管理。它被广泛应用于演出、活动、会议等场合&#xff0c;可以同时播放多个视频、图像和音频文件&#xff0c;并提供强大的控制和管理功能。 PVP2 ProVideoPlayer2具有直观的用…

Leetcode刷题详解——斐波那契数

1. 题目链接&#xff1a;509. 斐波那契数 2. 题目描述&#xff1a; 斐波那契数 &#xff08;通常用 F(n) 表示&#xff09;形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始&#xff0c;后面的每一项数字都是前面两项数字的和。也就是&#xff1a; F(0) 0&#xff0c;F(1…

【开源】基于Vue和SpringBoot的民宿预定管理系统

项目编号&#xff1a; S 058 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S058&#xff0c;文末获取源码。} 项目编号&#xff1a;S058&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 用例设计2.2 功能设计2.2.1 租客角色…

23111707[含文档+PPT+源码等]计算机毕业设计基于javawebmysql的旅游网址前后台-全新项目

文章目录 **软件开发环境及开发工具&#xff1a;****功能介绍&#xff1a;****论文截图&#xff1a;****实现&#xff1a;****代码:** 编程技术交流、源码分享、模板分享、网课教程 &#x1f427;裙&#xff1a;776871563 软件开发环境及开发工具&#xff1a; 前端使用技术&a…

JVM类加载机制详解

JVM类加载运行全过程 运行Math类的main函数&#xff0c;启动程序时&#xff0c;首先需要通过类加载器把类加载到JVM。 package com.cold;public class Math {public int compute() {int a 1;int b 2;int c (a b) * 10;return c;}public static void main(String[] args) …
最新文章