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

相关文章

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.