文章目录

  • Spring的事务控制
  • 编程式事务控制相关对象
    • PlatformTransactionManager
    • TransactionDefinition
      • 事务隔离级别
      • 事务传播行为
    • TransactionStatus
  • 基于XML的声明式事务控制
    • 什么是声明式事务控制
    • 转账业务环境搭建
      • 新建项目、导入相关依赖
      • 编写Dao层
      • 实体类
      • service层
      • 操作类
      • Spring.xml
        • jdbc.properties
      • 测试转账成功
    • 声明式事务控制的表现
      • 编辑spring.xml
      • 在业务成加个异常切入点
      • 成功测试
        • 运行
      • 不会滚事务的情况
        • 注销语句
        • 测试运行
    • 切点方法的事务参数的配置
  • 基于注解的声明式事务控制
    • 复制项目
      • 注解修改dao层
      • 注解修改service层
      • Spring.xml组件扫描
        • 我们删除一些配置,使用注解完成
        • 我们service层加注解(方式1)
        • 我们service层加注解(方式2)
        • 我们service层加注解(方式3)
        • Spring配置注解驱动
      • 成功测试
        • 转账成功
        • 转账失败

Spring的事务控制

编程式事务控制相关对象

PlatformTransactionManager

就是一个接口

TransactionDefinition

事务隔离级别

事务传播行为

TransactionStatus

基于XML的声明式事务控制

什么是声明式事务控制

转账业务环境搭建

新建项目、导入相关依赖

    <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.4</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.32</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies>

编写Dao层

package com.taotao.dao;import org.springframework.jdbc.core.JdbcTemplate;/*** create by 刘鸿涛* 2022/4/26 17:29*/
@SuppressWarnings({"all"})
public interface AccountDao {void setJdbcTemplate(JdbcTemplate jdbcTemplate);void out(String outMan,double money);void in(String inMan,double money);
}
package com.taotao.dao.impl;import com.taotao.dao.AccountDao;
import org.springframework.jdbc.core.JdbcTemplate;/*** create by 刘鸿涛* 2022/4/26 17:28*/
@SuppressWarnings({"all"})
public class AccountDaoImpl implements AccountDao {private JdbcTemplate jdbcTemplate;public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}public void out(String outMan, double money) {jdbcTemplate.update("update account set money = money-? where name=?",money,outMan);}public void in(String inMan, double money) {jdbcTemplate.update("update account set money=money+? where name=?",money,inMan);}
}

实体类

package com.taotao.domain;/*** create by 刘鸿涛* 2022/4/26 17:34*/
@SuppressWarnings({"all"})
public class Account {private String name;private double money;public String getName() {return name;}public void setName(String name) {this.name = name;}public double getMoney() {return money;}public void setMoney(double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"name='" + name + '\'' +", money=" + money +'}';}
}

service层

package com.taotao.service;import com.taotao.dao.AccountDao;/*** create by 刘鸿涛* 2022/4/26 17:37*/
@SuppressWarnings({"all"})
public interface AccountService {void setAccountDao(AccountDao accountDao);void transfer(String outMan,String inMan,double money);
}
package com.taotao.service.impl;import com.taotao.dao.AccountDao;
import com.taotao.service.AccountService;/*** create by 刘鸿涛* 2022/4/26 17:36*/
@SuppressWarnings({"all"})
public class AccountServiceImpl implements AccountService {private AccountDao accountDao;public void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}public void transfer(String outMan, String inMan, double money) {accountDao.out(outMan,money);accountDao.in(inMan,money);}
}

操作类

package com.taotao.controller;import com.taotao.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** create by 刘鸿涛* 2022/4/26 17:53*/
@SuppressWarnings({"all"})
public class AccountController {public static void main(String[] args) {ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");AccountService accountService = app.getBean(AccountService.class);accountService.transfer("ano","lucy",500);}
}

Spring.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 http://www.springframework.org/schema/context/spring-context.xsd"><!--    加载jdbc.properties--><context:property-placeholder location="classpath:jdbc.properties"/><!--    数据源对象--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--    jdbc模板对象--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean><bean id="accountDao" class="com.taotao.dao.impl.AccountDaoImpl"><property name="jdbcTemplate" ref="jdbcTemplate"/></bean><bean id="accountService" class="com.taotao.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"/></bean>
</beans>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/Test
jdbc.username=root
jdbc.password=12345

测试转账成功

声明式事务控制的表现

当数据异常时,终止提交事务

编辑spring.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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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.xsdhttp://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd
"><!--    加载jdbc.properties--><context:property-placeholder location="classpath:jdbc.properties"/><!--    数据源对象--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--    jdbc模板对象--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean><bean id="accountDao" class="com.taotao.dao.impl.AccountDaoImpl"><property name="jdbcTemplate" ref="jdbcTemplate"/></bean><!--    目标对象 内部的方法时切点--><bean id="accountService" class="com.taotao.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"/></bean><!--    配置平台事务管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--    通知 事务的增强--><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="*"/></tx:attributes></tx:advice><!--    配置事务的aop织入--><aop:config><aop:advisor advice-ref="txAdvice" pointcut="execution(* com.taotao.service.impl.*.*(..))"></aop:advisor></aop:config></beans>

在业务成加个异常切入点

当异常时,不提交数据

package com.taotao.service.impl;import com.taotao.dao.AccountDao;
import com.taotao.service.AccountService;/*** create by 刘鸿涛* 2022/4/26 17:36*/
@SuppressWarnings({"all"})
public class AccountServiceImpl implements AccountService {private AccountDao accountDao;public void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}public void transfer(String outMan, String inMan, double money) {accountDao.out(outMan,money);int i = 1 / 0;accountDao.in(inMan,money);}
}

成功测试

运行

不会滚事务的情况

注销语句

    <!--    配置事务的aop织入-->
<!--    <aop:config>-->
<!--        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.taotao.service.impl.*.*(..))"></aop:advisor>-->
<!--    </aop:config>-->

测试运行

钱少了500

切点方法的事务参数的配置

基于注解的声明式事务控制

复制项目

注解修改dao层

package com.taotao.dao.impl;import com.taotao.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;/*** create by 刘鸿涛* 2022/4/26 17:28*/
@SuppressWarnings({"all"})
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {@Autowiredprivate JdbcTemplate jdbcTemplate;public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}public void out(String outMan, double money) {jdbcTemplate.update("update account set money = money-? where name=?",money,outMan);}public void in(String inMan, double money) {jdbcTemplate.update("update account set money=money+? where name=?",money,inMan);}
}

注解修改service层

package com.taotao.service.impl;import com.taotao.dao.AccountDao;
import com.taotao.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** create by 刘鸿涛* 2022/4/26 17:36*/
@SuppressWarnings({"all"})
@Service("accountService")
public class AccountServiceImpl implements AccountService {private AccountDao accountDao;@Autowiredpublic void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}public void transfer(String outMan, String inMan, double money) {accountDao.out(outMan,money);int i = 1 / 0;accountDao.in(inMan,money);}
}

Spring.xml组件扫描

注意context命名空间配置

<!--    组件扫描--><context:component-scan base-package="com.taotao"/>

我们删除一些配置,使用注解完成

下面的都删除

    <!--    通知 事务的增强--><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="*"/></tx:attributes></tx:advice><!--        配置事务的aop织入--><aop:config><aop:advisor advice-ref="txAdvice" pointcut="execution(* com.taotao.service.impl.*.*(..))"></aop:advisor></aop:config>

我们service层加注解(方式1)

package com.taotao.service.impl;import com.taotao.dao.AccountDao;
import com.taotao.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;/*** create by 刘鸿涛* 2022/4/26 17:36*/
@SuppressWarnings({"all"})
@Service("accountService")
public class AccountServiceImpl implements AccountService {private AccountDao accountDao;@Autowiredpublic void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)public void transfer(String outMan, String inMan, double money) {accountDao.out(outMan,money);
//        int i = 1 / 0;accountDao.in(inMan,money);}@Transactional(isolation = Isolation.DEFAULT)public void xxx(){}
}

我们service层加注解(方式2)

package com.taotao.service.impl;import com.taotao.dao.AccountDao;
import com.taotao.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;/*** create by 刘鸿涛* 2022/4/26 17:36*/
@SuppressWarnings({"all"})
@Service("accountService")
@Transactional(isolation = Isolation.REPEATABLE_READ)
public class AccountServiceImpl implements AccountService {private AccountDao accountDao;@Autowiredpublic void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}public void transfer(String outMan, String inMan, double money) {accountDao.out(outMan,money);
//        int i = 1 / 0;accountDao.in(inMan,money);}public void xxx(){}
}

我们service层加注解(方式3)

就近原则

package com.taotao.service.impl;import com.taotao.dao.AccountDao;
import com.taotao.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;/*** create by 刘鸿涛* 2022/4/26 17:36*/
@SuppressWarnings({"all"})
@Service("accountService")
@Transactional(isolation = Isolation.REPEATABLE_READ)
public class AccountServiceImpl implements AccountService {private AccountDao accountDao;@Autowiredpublic void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}@Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED)public void transfer(String outMan, String inMan, double money) {accountDao.out(outMan,money);
//        int i = 1 / 0;accountDao.in(inMan,money);}public void xxx(){}
}

Spring配置注解驱动

<?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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.xsdhttp://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd
"><!--    组件扫描--><context:component-scan base-package="com.taotao"/><!--    加载jdbc.properties--><context:property-placeholder location="classpath:jdbc.properties"/><!--    数据源对象--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--    jdbc模板对象--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean><bean id="accountDao" class="com.taotao.dao.impl.AccountDaoImpl"><property name="jdbcTemplate" ref="jdbcTemplate"/></bean><!--    目标对象 内部的方法时切点--><bean id="accountService" class="com.taotao.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"/></bean><!--    配置平台事务管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--    事务的注解驱动--><tx:annotation-driven transaction-manager="transactionManager"/></beans>

成功测试

转账成功

转账失败

事务中断,不提交

        accountDao.out(outMan,money);int i = 1 / 0;accountDao.in(inMan,money);

Spring - Spring事务控制详解与案例总结相关推荐

  1. Spring Boot事务管理详解

    什么是事务? 我们在开发企业应用时,对于业务人员的一个操作实际是对数据读写的多步操作的结合.由于数据操作在顺序执行的过程中,任何一步操作都有可能发生异常,异常会导致后续操作无法完成,此时由于业务逻辑并 ...

  2. Spring事务管理详解_基本原理_事务管理方式

    Spring事务管理详解_基本原理_事务管理方式 1. 事务的基本原理 Spring事务的本质其实就是数据库对事务的支持,使用JDBC的事务管理机制,就是利用java.sql.Connection对象 ...

  3. 关于事务管理的理解和Spring事务管理详解

    转载于:http://www.mamicode.com/info-detail-1248286.html 1 初步理解 理解事务之前,先讲一个你日常生活中最常干的事:取钱. 比如你去ATM机取1000 ...

  4. Spring Boot 集成 FreeMarker 详解案例

    年轻就不应该让自己过得太舒服" – From yong 一.Springboot 那些事 SpringBoot 很方便的集成 FreeMarker ,DAO 数据库操作层依旧用的是 Myba ...

  5. spring框架 AOP核心详解

    AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想,是个比较经典的例子. 一 AOP的基本概念 (1)Asp ...

  6. spring batch item writer详解

    spring batch item writer详解 ItemWrite ItemWriter ItemStream 系统写组件 写数据库 JdbcBatchItemWriter JpaItemWri ...

  7. java 消息队列详解_Java消息队列-Spring整合ActiveMq的详解

    本篇文章主要介绍了详解Java消息队列-Spring整合ActiveMq ,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 1.概述 首先和大家一起回顾一下Java 消息服 ...

  8. Spring Cloud限流详解(附源码)

    在高并发的应用中,限流往往是一个绕不开的话题.本文详细探讨在Spring Cloud中如何实现限流. 在 Zuul 上实现限流是个不错的选择,只需要编写一个过滤器就可以了,关键在于如何实现限流的算法. ...

  9. Spring Cloud限流详解(内含源码)

    为什么80%的码农都做不了架构师?>>>    原文:http://www.itmuch.com/spring-cloud-sum/spring-cloud-ratelimit/ 在 ...

  10. SpringBoot2.1.5(16)--- Spring Boot的日志详解

    SpringBoot2.1.5(16)--- Spring Boot的日志详解 市面上有许多的日志框架,比如 JUL( java.util.logging), JCL( Apache Commons ...

最新文章

  1. Android网络编程系列 一 Socket抽象层
  2. C罗还会是史上第一个上链的得分王吗?
  3. 定时器工作原理及初值快速计算
  4. 【开源推荐】AllJoyn:打造全球物联网的通用开源框架
  5. [java] javax.el.PropertyNotFoundException: Property 'id' not found on type bean.Student
  6. C++面试题目(五)
  7. Leetcode 950. Reveal Cards In Increasing Order
  8. pip install 报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in
  9. 用计算机充手机吗,电脑充电器可以充手机吗
  10. [c#] const 与 readonly
  11. Just Pour the Water ZOJ - 2974 (矩阵快速幂)
  12. 模拟tcp_TCP 半连接队列和全连接队列满了会发生什么?又该如何应对?
  13. Spring Cloud 菜鸟教程 1 简介
  14. 区块链技术在银行业的应用
  15. 网页换肤--setAttribute - css
  16. 终于找到YST的BLOG了!!!!
  17. CSS mix-blend-mode滤色screen混合模式
  18. 跨平台应用开发进阶(十一) :uni-app 实现IOS原生APP-云打包集成极光推送(JG-JPUSH)详细教程
  19. 未来五年 LED智慧透明屏未来3大发展趋势
  20. SAP MM批次管理(1)物料与批次--大海

热门文章

  1. .NET前后分离解决方案
  2. 深度解析种子轮、天使轮、PreA轮、A轮、B轮、C轮的内涵
  3. 编译原理-18-语法分析实验代码示例
  4. python中%s是什么意思_python的%s是什么意思
  5. 谷歌人机图像识别接口
  6. JavaScript(1)使用ducument.write()在页面上显示红色的“开启JavaScript学习之旅”。
  7. DNA甲基化经CTCF和黏连蛋白复合体调节RNA可变剪切
  8. linux gmail邮件服务器,gmail 授权linux服务器登录使用gmail发送邮件
  9. python训练100题_Python练习100题
  10. UESTC_树上战争 CDOJ 32