Spring中使用事务搭建转账环境 转账操作一个账户要减少资金操作一个账户要增加资金操作,如果在两个操作间出现异常转账失败 所以要使用事务

本文主要是介绍Spring中使用事务搭建转账环境 转账操作一个账户要减少资金操作一个账户要增加资金操作,如果在两个操作间出现异常转账失败 所以要使用事务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

演示不使用事务出现异常情况

Dao层两个方法lessMoney()和moreMoney()

package com.swift;import org.springframework.jdbc.core.JdbcTemplate;public class AccountDao {private JdbcTemplate jdbcTemplate;public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}//少钱的方法public void lessMoney(String from,double number) {String sql="update account set money=money-? where username=?";jdbcTemplate.update(sql, number,from);}//多钱的方法public void moreMoney(String to,double number) {String sql="update account set money=money+? where username=?";jdbcTemplate.update(sql, number,to);}
}

Service层调用两个方法

package com.swift;public class AccountService {private AccountDao accountDao;public void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}public void moneyTransfer(String from,String to,double number) {accountDao.lessMoney(from,number);int i=10/0;accountDao.moreMoney(to,number);}
}

但是两个操作减与加之间,如果出现异常,则会导致转账钱已经转了,但对方却没有到账的bug,可能服务器突然故障等引起


 

解决添加事务,出现异常进行回滚操作

下面使用配置文件的方法进行事务管理

没有改变的测试类

package com.swift;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;@WebServlet("/test")
public class ServletTest extends HttpServlet {private static final long serialVersionUID = 1L;public ServletTest() {super();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");response.getWriter().append("Served at: ").append(request.getContextPath());//使用JdbcTemplat的queryForObject方法ApplicationContext context=new ClassPathXmlApplicationContext("c3p0.xml");AccountService accountService= (AccountService) context.getBean("accountService");accountService.moneyTransfer("佣兵组织", "高扬", 100000);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

使用配置文件进行事务处理步骤如下:

<?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"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- c3p0连接池得到dataSource --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sw_database"></property><property name="user" value="root"></property><property name="password" value="root"></property></bean><!-- 第一步 配置事务管理器 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 注入dataSource --><property name="dataSource" ref="dataSource"></property></bean><!-- 第二步 配置事务增强 --><tx:advice id="txadvice" transaction-manager="transactionManager"><!-- 做事务操作 --><tx:attributes><!-- 事务操作的方法匹配规则 --><tx:method name="money*" propagation="REQUIRED"/></tx:attributes></tx:advice><!-- 第三步 配置切面 --><aop:config><!-- 切入点 --><aop:pointcut expression="execution(* com.swift.AccountService.*(..))" id="pointcut1"/><!-- 切面 --><aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1"/></aop:config><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><bean id="accountDao" class="com.swift.AccountDao"><property name="jdbcTemplate" ref="jdbcTemplate"></property></bean><bean id="accountService" class="com.swift.AccountService"><property name="accountDao" ref="accountDao"></property></bean></beans>

分三个步骤 管理 增强和切面

虽然还是会有异常,但是数据库中不会出错,不会钱转出了,却没有到账

工具类Account

package com.swift;public class Account {private int id;private String username;private String money;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getMoney() {return money;}public void setMoney(String money) {this.money = money;}public Account(int id, String username, String money) {this.id = id;this.username = username;this.money = money;}public Account() {super();// TODO Auto-generated constructor stub
    }@Overridepublic String toString() {return "Account [id=" + id + ", username=" + username + ", money=" + money + "]";}}

 

这篇关于Spring中使用事务搭建转账环境 转账操作一个账户要减少资金操作一个账户要增加资金操作,如果在两个操作间出现异常转账失败 所以要使用事务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/762193

相关文章

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.