Spring事物处理规则:

运行时异常,默认回滚。

编译异常,默认提交。

事物案例:购买股票

数据库脚本

/*
SQLyog v10.2
MySQL - 5.6.24 : Database - y2167
*********************************************************************
*//*!40101 SET NAMES utf8 */;/*!40101 SET SQL_MODE=''*/;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`y2167` /*!40100 DEFAULT CHARACTER SET utf8 */;USE `y2167`;/*Table structure for table `account` */DROP TABLE IF EXISTS `account`;CREATE TABLE `account` (`aid` INT(11) NOT NULL AUTO_INCREMENT,`aname` VARCHAR(20) DEFAULT NULL,`balance` INT(11) DEFAULT NULL,PRIMARY KEY (`aid`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;/*Data for the table `account` */insert  into `account`(`aid`,`aname`,`balance`) values (1,'xcq',60000);/*Table structure for table `stock` */DROP TABLE IF EXISTS `stock`;CREATE TABLE `stock` (`sid` int(11) NOT NULL AUTO_INCREMENT,`sname` varchar(30) DEFAULT NULL,`count` int(11) DEFAULT NULL,PRIMARY KEY (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;/*Data for the table `stock` */insert  into `stock`(`sid`,`sname`,`count`) values (1,'股票A',5),(2,'股票B',20),(3,'股票C',30);/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

创建DAO和Service层

//DAO层package cn.happy.day15tx.dao;/*** Created by Administrator on 2018/3/14.*/
//账户
public interface IAccountDAO {public void updateAccount(int aid,int balance,boolean isBuy);
}-------------------------------------------------------------------------public interface IStockDAO {//改变股票数量public void updateIStock(int sid,int count,boolean isBuy);
}-------------------------------------------------------------------------

//DAOImplpackage cn.happy.day15tx.dao.impl;import cn.happy.day15tx.dao.IStockDAO;
import org.springframework.jdbc.core.support.JdbcDaoSupport;/*** Created by Administrator on 2018/3/14.*///卖出
public class StockDaoImpl extends JdbcDaoSupport implements IStockDAO {public void updateIStock(int sid, int count, boolean isBuy) {String sql=null;if(isBuy){//增加股票sql="update Stock set count=count+? where sid=?";}else{//卖出股票sql="update Stock set count=count-? where sid=?";}this.getJdbcTemplate().update(sql,count,sid);}
}-------------------------------------------------------------------------package cn.happy.day15tx.dao.impl;import cn.happy.day15tx.dao.IAccountDAO;
import org.springframework.jdbc.core.support.JdbcDaoSupport;/*** Created by Administrator on 2018/3/14.*///买入
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDAO {public void updateAccount(int aid, int balance, boolean isBuy) {String sql=null;if(isBuy){//购买sql="update Account set balance=balance-? where aid=?";}else{//卖出sql="update Account set balance=balance+? where aid=?";}this.getJdbcTemplate().update(sql,balance,aid);}
}
------------------------------------------------------------------------
Servicepackage cn.happy.day15tx.service;/*** Created by Administrator on 2018/3/14.*/
public interface IStockService {//购买股票public void updateStock(int aid,int balance,int sid,int count) throws Exception, Exception;
}------------------------------------------------------------------------
ServiceImplpackage cn.happy.day15tx.service.impl;import cn.happy.day15tx.dao.IAccountDAO;
import cn.happy.day15tx.dao.IStockDAO;
import cn.happy.day15tx.service.IStockService;
import com.sun.javafx.beans.annotations.Default;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;/*** Created by Administrator on 2018/3/14.*/public class StockServiceImpl implements IStockService {//植入DAO层对象private IAccountDAO accountDAO;private IStockDAO iStockDAO;//使用注解@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)public void updateStock(int aid, int balance, int sid, int count) throws Exception {//创建boolean对象判断是买入true还是卖出falseboolean isBuy=true;accountDAO.updateAccount(aid,balance,isBuy);//定义一个异常if(true)throw new Exception("出错了");iStockDAO.updateIStock(sid,count,isBuy);}public IAccountDAO getAccountDAO() {return accountDAO;}public void setAccountDAO(IAccountDAO accountDAO) {this.accountDAO = accountDAO;}public IStockDAO getiStockDAO() {return iStockDAO;}public void setiStockDAO(IStockDAO iStockDAO) {this.iStockDAO = iStockDAO;}
}

-------------------------------------------------------------entity

package cn.happy.day15tx.entity;

/** * Created by Administrator on 2018/3/14. *///购票类public class Account {    private Integer aid;    private String aname;    private Integer balance;

    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 getBalance() {        return balance;    }

    public void setBalance(Integer balance) {        this.balance = balance;    }}

-------------------------------------------------------
package cn.happy.day15tx.entity;

/** * Created by Administrator on 2018/3/14. *///股票类public class Stock {    private Integer sid;    private String sname;    private Integer count;

    public Integer getSid() {        return sid;    }

    public void setSid(Integer sid) {        this.sid = sid;    }

    public String getSname() {        return sname;    }

    public void setSname(String sname) {        this.sname = sname;    }

    public Integer getCount() {        return count;    }

    public void setCount(Integer count) {        this.count = count;    }}


一、配置xml文件

<!--数据源--><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--识别jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--DAO--><bean id="StockDAO" class="cn.happy.day15tx.dao.impl.StockDaoImpl"><property name="dataSource" ref="dataSource"/></bean><bean id="AccountDAO" class="cn.happy.day15tx.dao.impl.AccountDaoImpl"><property name="dataSource" ref="dataSource"/></bean><!--service--><bean id="StockService" class="cn.happy.day15tx.service.impl.StockServiceImpl"><property name="accountDAO" ref="AccountDAO"/><property name="iStockDAO" ref="StockDAO"/></bean><!--事物管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--事物控制--><!--方案一--><bean id="stockServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"><property name="transactionManager" ref="transactionManager"/><!--需要控制的类--><property name="target" ref="StockService"/><property name="transactionAttributes"><props><!--控制的方法--><prop key="updateStock">ISOLATION_DEFAULT,PROPAGATION_REQUIRED,-Exception</prop>          <!--            ISOLATION_DEFAULT   底层数据库默认隔离级别            PROPAGATION_REQUIRED 如果当前没有事务,就创建一个新事务,如果当前存在事务,就加入该事务            -Exception,设置回滚(设置异常,只要出现运行时异常就会回滚)
          -->       </props>     </property>   </bean>

  

测试方法

package day15tx;import cn.happy.JDBCTemplate.service.BookService;
import cn.happy.day15tx.service.IStockService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.List;/*** Created by Administrator on 2018/3/3.*/
public class Test20180314 {//事物@Testpublic void Spring(){ApplicationContext ctx=new ClassPathXmlApplicationContext("day15tx.xml");IStockService service=(IStockService)ctx.getBean("stockServiceProxy");try{service.updateStock(1,2000,1,5);}catch (Exception e){e.printStackTrace();}}}

  

二、使用注解管理事物

<?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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"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/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"><!--数据源--><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--识别jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--DAO--><bean id="StockDAO" class="cn.happy.day15tx.dao.impl.StockDaoImpl"><property name="dataSource" ref="dataSource"/></bean><bean id="AccountDAO" class="cn.happy.day15tx.dao.impl.AccountDaoImpl"><property name="dataSource" ref="dataSource"/></bean><!--service--><bean id="StockService" class="cn.happy.day15tx.service.impl.StockServiceImpl"><property name="accountDAO" ref="AccountDAO"/><property name="iStockDAO" ref="StockDAO"/></bean><!--事物管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--方案二:使用注解管理事物--><tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven></beans>

  

在需要管理的方法上添加注解

 @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)

  

三、使用AspectJ实现事物管理

<?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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"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/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"><!--数据源--><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--识别jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--DAO--><bean id="StockDAO" class="cn.happy.day15tx.dao.impl.StockDaoImpl"><property name="dataSource" ref="dataSource"/></bean><bean id="AccountDAO" class="cn.happy.day15tx.dao.impl.AccountDaoImpl"><property name="dataSource" ref="dataSource"/></bean><!--service--><bean id="StockService" class="cn.happy.day15tx.service.impl.StockServiceImpl"><property name="accountDAO" ref="AccountDAO"/><property name="iStockDAO" ref="StockDAO"/></bean><!--事物管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--方案三:使用aspectJ AOP实现事物管理--><!-- <tx:advice id="advice" transaction-manager="transactionManager"><tx:attributes><tx:method name="updateStock" isolation="DEFAULT" rollback-for="Exception"/></tx:attributes></tx:advice><aop:config><!–切点–><aop:pointcut id="mypoint" expression="execution(* *..day15tx.service.*.*(..))"></aop:pointcut><!–顾问–><aop:advisor advice-ref="advice" pointcut-ref="mypoint"></aop:advisor></aop:config>--></beans>

  

转载于:https://www.cnblogs.com/xuchangqi1/p/8581634.html

Spring事物管理(二)相关推荐

  1. MyBatis6:MyBatis集成Spring事物管理(下篇)

    前言 前一篇文章<MyBatis5:MyBatis集成Spring事物管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事物的做法,本文的目的是在这个的基 ...

  2. 5.3 Spring事物管理详解 我的程序猿之路:第四十二章

    目录 1.事务介绍 2.事务的四个特性(ACID) 3.Spring 事务管理的核心接口 4. PlatformTransactionManager  事务管理器 5.TransactionStatu ...

  3. spring事物管理--声明式(AspectJ)注解实现 (推荐使用)

    1.表结构及数据 2.使用的jar包 3.service.Dao层接口与实现类: Dao接口: //转账案例持久层接口 public interface AccountDao {/*** @param ...

  4. spring事物管理

    一)spring的事务管理      事务管理并非spring独有,用过JDBC hibernate的朋友都知道,这些api和框架都提供了自己的事务管理机制.那么spring的事务管理又有些什么与众不 ...

  5. Spring事务管理(二)-TransactionProxyFactoryBean原理

    2019独角兽企业重金招聘Python工程师标准>>> 通常Spring事务管理的配置都是XML或者声明式注解的方式,然后想要学习其运行的原理,从TransactionProxyFa ...

  6. Spring事物管理器TransactionManager解析

    Spring框架支持事务管理的核心是事务管理器抽象,对于不同的数据访问框架(如Hibernate)通过实现策略接口PlatformTransactionManager,从而能支持各种数据访问框架的事务 ...

  7. spring事物管理(配置文件方式)

    1 <!-- 配置c3p0连接池 --> 2 <bean id="dataSource" class="com.mchange.v2.c3p0.Comb ...

  8. Spring事务管理(三)-PlatformmTransactionManager解析和事务传播方式原理

    2019独角兽企业重金招聘Python工程师标准>>> Spring在事务管理时,对事务的处理做了极致的抽象,即PlatformTransactionManager.对事务的操作,简 ...

  9. Spring事务管理全面分析

    Spring 事务属性分析 什么是事物   事务管理对于企业应用而言至关重要.它保证了用户的每一次操作都是可靠的,即便出现了异常的访问情况,也不至于破坏后台数据的完整性.就像银行的自助取款机,通常都能 ...

最新文章

  1. 实验四:使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
  2. Unity2D游戏开发基础教程1.2 项目、资源和场景
  3. 哥伦比亚大学计算机工程面试题
  4. Stark 组件:快速开发神器 —— 自动生成 URL
  5. [渝粤教育] 山东第一医科大学 健康教育与健康促进 参考 资料
  6. python索引值_python索引总结
  7. 【MySql】100问
  8. 功率因数cosφ仪表盘
  9. 查询linux下的业务端口,Linux系统查询显示端口信息用什么命令
  10. 25.redux中间件redux-thunk和redux-saga
  11. nginx配置地址端口
  12. COLA 2.0架构应用
  13. JSP实现简单的登录页面实现及代码(非连接数据库)
  14. 盘点国内十大免费CDN提供商
  15. P4844 LJJ爱数数
  16. DophinScheduler server部分 核心代码详细解析——掌控任务和进程的呼吸与脉搏:log、monitor与registry
  17. 天下所有的事,都是为了利益,都是按利益逻辑规律在运行,发生的一切事情都可以用利益逻辑来解释。
  18. 【图解HTTP】确保WEB安全的HTTPS
  19. CAD-VB多段线、波浪线、射线、构造线
  20. 城市景观生态规划概述

热门文章

  1. 电脑应用程序错误怎么办_遇到电脑桌面应用程序无法正常启动(0xc0000142)怎么办?0xc0000142解决方法...
  2. html图像排列代码,HTML图像(示例代码)
  3. python中circle函数的用法,python画圆运用了什么函数
  4. oracle二进制转换字母,如何将oracle二进制数据转换为word文本
  5. 安卓蓝牙键盘切换输入法_超薄无线蓝牙双模罗技K580键盘,自由切换享受打字快乐...
  6. 学web前端有什么计划?
  7. pyqt5 不报错退出_最新版本Python图形化开发环境Anaconda(Python3.7) +PyQT5+Eric6
  8. 以太坊PHP离线交易签名生成,以太坊web3.sendRawTransaction离线签名交易
  9. 组合体计算机绘图的实验原理,机械制图及计算机绘图
  10. Java中GUI中菜单栏