Spring 事务操作(银行转账案例),使用spring 对jdbc的支持完成对数据库的操作

来源:互联网 发布:苏州博奕思网络 编辑:程序博客网 时间:2024/05/17 10:42

Spring 事务操作(银行转账案例),使用spring 对jdbc的支持完成对数据库的操作


本人演示的是转账案例,当A用户给B用户转账时先要减去A用户的金额,然后在B用户的金额上加上A用户给B用户转账方金额,这是一个完整的业务,中间不能出现问题。A账户减钱和B账户加钱两件事情要么同时成功,要么失败。所以这里就需要使用事务。下面将演示事务的使用,本人使用spring对jdbc的支持对数据库进行操作。配置事务本人使用的是基于配置文件的方式。

本人在数据库中创建了一张账户表,表的结构如下,并填充如下的数据:






注:这里的数据表的引擎必须为  InnoDB 否则事务操作失败


下面是本人的演示项目:

项目结构:



IAccountDAO.java 转账接口,提供添加金额和减少金额的方法,AccountDAOImpl.java 为接口的实现类,Account.java 为账户实体类,IAccountService.java 为 service 接口提供转账业务方法,AccountServiceImpl.java 为转账业务方法的实现类,Test.java 为测试类,applicationContext.xml 为spring的主配置文件,在里面进行了数据库的配置,创建bean,进行事务的配置,log4j.properties 为日志文件。


本人在AccountServiceImpl.java 中自己制定了一个空指针异常,方便我们观察事务的作用

// 这里我们让查询出一个空指针异常,然后我们观察转账业务是否成功String str = null;str.length();

说明:本项目使用c3p0数据源


所需要的jar包:



下面是各个类的代码:

1、IAccountDAO.java 转账接口 提供添加金额和减少金额的方法

package cn.sz.hcq.dao;public interface IAccountDAO {/** * 增加方法 *  * @param aid * @param money */public void addMoney(Integer aid, Integer money);/** * 减款方法 *  * @param aid * @param money */public void subMoney(Integer aid, Integer money);}


2、AccountDAOImpl.java 为接口的实现类

package cn.sz.hcq.dao.impl;import org.springframework.jdbc.core.JdbcTemplate;import cn.sz.hcq.dao.IAccountDAO;public class AccountDAOImpl implements IAccountDAO {// 利用spring对jdbc的支持进行操作private JdbcTemplate template;@Overridepublic void addMoney(Integer aid, Integer money) {String sql = "update sz_account set money=money+? where aid=?";template.update(sql, money, aid);}@Overridepublic void subMoney(Integer aid, Integer money) {String sql = "update sz_account set money=money-? where aid=?";template.update(sql, money, aid);}public JdbcTemplate getTemplate() {return template;}public void setTemplate(JdbcTemplate template) {this.template = template;}}



3、Account.java 为账户实体类

package cn.sz.hcq.pojo;import java.io.Serializable;public class Account implements Serializable {private Integer aid;private String aname;private Integer money;public Integer getAid() {return aid;}public void setAid(Integer aid) {this.aid = aid;}public String getAname() {return aname;}public void setAname(String aname) {this.aname = aname;}public Integer getMoney() {return money;}public void setMoney(Integer money) {this.money = money;}}



4、IAccountService.java 为 service 接口提供转账业务方法

package cn.sz.hcq.service;public interface IAccountService {/** * 用户转账业务 * @param from 转账人 * @param to 接收方 * @param money 转账金额 */public void account(Integer from, Integer to, int money);}



5、AccountServiceImpl.java 为转账业务方法的实现类

package cn.sz.hcq.service.impl;import cn.sz.hcq.dao.IAccountDAO;import cn.sz.hcq.service.IAccountService;public class AccountServiceImpl implements IAccountService {private IAccountDAO accountDAOImpl;@Overridepublic void account(Integer from, Integer to, int money) {// 转账方转出accountDAOImpl.subMoney(from, money);// 这里我们让查询出一个空指针异常,然后我们观察转账业务是否成功String str = null;str.length();// 收款方转入accountDAOImpl.addMoney(to, money);}public IAccountDAO getAccountDAOImpl() {return accountDAOImpl;}public void setAccountDAOImpl(IAccountDAO accountDAOImpl) {this.accountDAOImpl = accountDAOImpl;}}



6、applicationContext.xml 为spring的主配置文件,在里面进行了数据库的配置,创建bean,进行事务的配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx.xsd        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd"><!--这里使用c3p0数据源 --><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/db?characterEncoding=utf8"></property><property name="user" value="root"></property><property name="password" value="root"></property><property name="initialPoolSize" value="10"></property><property name="maxIdleTime" value="30"></property><property name="maxPoolSize" value="100"></property><property name="minPoolSize" value="10"></property><property name="maxStatements" value="200"></property></bean><!-- 创建JdbcTemplate对象完成对数据库的操作 --><bean id="template" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><bean id="accountDAOImpl" class="cn.sz.hcq.dao.impl.AccountDAOImpl"><property name="template" ref="template"></property></bean><bean id="accountServiceImpl" class="cn.sz.hcq.service.impl.AccountServiceImpl"><property name="accountDAOImpl" ref="accountDAOImpl"></property></bean><!-- 实现事务配置 --><!-- 创建一个管理事务的对象 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><tx:advice id="txadvice" transaction-manager="transactionManager"><tx:attributes><!-- 设置进行事务操作的方法匹配规则,即在做哪些方法的调用时实现哪种事务隔离级别设置 --><tx:method name="account*" propagation="REQUIRED" /><!-- <tx:method name="accountMoney"/> <tx:method name="insert*"/> *号表示凡是带有accountxxx的方法均添加事务管理;propagation配置事务隔离级别 --></tx:attributes></tx:advice><aop:config><!-- 切入点 --><aop:pointcutexpression="execution(* cn.sz.hcq.service.impl.AccountServiceImpl.*(..))"id="p" /><!-- 切面,即将事务管理添加到指定的方法 --><aop:advisor advice-ref="txadvice" pointcut-ref="p" /></aop:config></beans>



7、log4j.properties 为日志文件

log4j.rootLogger=DEBUG,console,FILElog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.threshold=INFOlog4j.appender.console.layout=org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%5p] - %c -%F(%L) -%m%nlog4j.appender.FILE=org.apache.log4j.RollingFileAppenderlog4j.appender.FILE.maxBackupIndex=100##log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender log4j.appender.FILE.Append=truelog4j.appender.FILE.File=c:/error1.loglog4j.appender.FILE.Threshold=INFOlog4j.appender.FILE.layout=org.apache.log4j.PatternLayoutlog4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%5p] - %c -%F(%L) -%m%nlog4j.appender.FILE.MaxFileSize=1MB



8、Test.java 为测试类

package cn.sz.hcq.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.sz.hcq.service.IAccountService;public class Test {public static void main(String[] args) {// 读取主配置文件ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");// 获取到转账的对象IAccountService ai = ac.getBean("accountServiceImpl",IAccountService.class);ai.account(1, 2, 100);// 用户1向用户2转账100}}



完成代码后运行测试类,发现转账失败了,用户1的金额没有减少,用户2的金额也没有增加,所以事务发挥了作用(我们在转账业务方法中制定了空指针异常)。



当我们把自己制定的异常注释后,运行测试类,发现用户1的金额减少了,用户2 的金额也增加了。


以上就是spring事务的使用案例。




原创粉丝点击