Spring 事务控制

Spring 事务控制介绍

JavaEE 体系进行分层开发,事务控制位于业务层,Spring 提供了分层设计业务层的事务处理解决方案。

Spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。但是推荐以配置的方式实现

PlatformTransactionManager 接口是提供事务操作的方法,它包含的获取事务状态信息、提交事务、回滚事务等方法。

DataSourceTransactionManager 实现类用于 Spring JdbcTemplate 或 MyBatis 持久化数据。

事务的传播行为

  • REQUIRED 如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般用于增删改操作
  • SUPPORTS 支持当前事务,如果当前没有事务,就以非事务方式执行。一般用于查操作
  • MANDATORY 使用当前的事务,如果当前没有事务,就抛出异常
  • REQUERS_NEW 新建事务,如果当前在事务中,把当前事务挂起
  • NOT_SUPPORTED 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
  • NEVER 以非事务方式运行,如果当前存在事务,抛出异常
  • NESTED 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作

XML 的 事务控制

本节源码

使用步骤

  • 创建 Spring 的配置文件并导入约束
  • 准备数据库表和实体类
  • 编写持久层接口和实现类
  • 编写业务层接口和实现类
  • 编写配置文件
    • 在配置文件中配置持久层和业务
    • 配置数据源
    • 配置事务相关:
      • 配置事务管理器
      • 配置事务的通知
        • 配置事务的属性
      • 配置 AOP
        • 配置 AOP 切入点表达式
        • 配置切入点表达式和事务通知的对应关系

账户的持久层接口的实现类:AccountDAOImpl.java

package cn.parzulpan.dao;

import cn.parzulpan.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import java.util.List; /**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 账户的持久层接口的实现类
*/ public class AccountDAOImpl extends JdbcDaoSupport implements AccountDAO { public Account findById(Integer accountId) {
List<Account> accounts = getJdbcTemplate().query("select * from bankAccount where id = ?",
new BeanPropertyRowMapper<Account>(Account.class),
accountId);
return accounts.isEmpty() ? null : accounts.get(0);
} public Account findByName(String name) {
List<Account> accounts = getJdbcTemplate().query("select * from bankAccount where name = ?",
new BeanPropertyRowMapper<Account>(Account.class),
name);
if (accounts.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
} public void update(Account account) {
getJdbcTemplate().update("update bankAccount set name = ?, money = ? where id = ?",
account.getName(), account.getMoney(), account.getId());
}
}

账户的持久层接口的实现类:AccountServiceImpl.java

package cn.parzulpan.service;

import cn.parzulpan.dao.AccountDAO;
import cn.parzulpan.domain.Account; /**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 账户的业务层接口的实现类,事务控制应该在业务层
*/ public class AccountServiceImpl implements AccountService {
private AccountDAO accountDAO; public void setAccountDAO(AccountDAO accountDAO) {
this.accountDAO = accountDAO;
} public Account findById(Integer accountId) {
return accountDAO.findById(accountId);
} public void transfer(String sourceName, String targetName, Double money) {
System.out.println("开始进行转账..."); Account source = accountDAO.findByName(sourceName);
Account target = accountDAO.findByName(targetName);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDAO.update(source);
int i = 1 / 0; // 模拟转账故障
accountDAO.update(target); System.out.println("转账完成...");
}
}

配置文件:bean.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 配置账户业务层 -->
<bean id="accountService" class="cn.parzulpan.service.AccountServiceImpl">
<property name="accountDAO" ref="accountDAO"/>
</bean> <!-- 配置账户持久层 -->
<bean id="accountDAO" class="cn.parzulpan.dao.AccountDAOImpl">
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springT?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean> <!-- 1. 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 2. 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 3. 配置事务的属性
指定是业务核心方法
read-only:是否是只读事务。默认 false,不只读。
isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
propagation:指定事务的传播行为。
timeout:指定超时时间。默认值为:-1。永不超时。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。
没有默认值,任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。
没有默认值,任何异常都回滚。
-->
<tx:attributes>
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<!-- 查询方法 -->
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice> <!-- 4. 配置 AOP -->
<aop:config>
<!-- 5. 配置 AOP 切入点表达式 -->
<aop:pointcut id="allServiceImplPCR" expression="execution(* cn.parzulpan.service.*.*(..))"/>
<!-- 6. 配置切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="allServiceImplPCR"/>
</aop:config> </beans>

对 账户的业务层 进行单元测试:AccountServiceImplTest.java

package cn.parzulpan.service;

import cn.parzulpan.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; /**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 对 账户的业务层 进行单元测试
*/ @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceImplTest { @Autowired
private AccountService as; @Test
public void findById() {
Account account = as.findById(1);
System.out.println(account);
} @Test
public void transfer() {
as.transfer("aaa", "bbb", 100.0);
}
}

注解 的 事务控制

本节源码

使用步骤

  • 其他同 XML 的 事务控制
  • 编写配置文件
    • 配置事务管理器
    • 开启对注解事务的支持
    • 在需要事务支持的地方使用 @Transactional

账户的持久层接口的实现类:AccountDAOImpl.java

package cn.parzulpan.dao;

import cn.parzulpan.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository; import javax.annotation.Resource;
import java.util.List; /**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 账户的持久层接口的实现类
*/ @Repository("accountDAO")
public class AccountDAOImpl implements AccountDAO {
@Resource(name = "jdbcTemplate")
private JdbcTemplate jdbcTemplate; public Account findById(Integer accountId) {
List<Account> accounts = jdbcTemplate.query("select * from bankAccount where id = ?",
new BeanPropertyRowMapper<Account>(Account.class),
accountId);
return accounts.isEmpty() ? null : accounts.get(0);
} public Account findByName(String name) {
List<Account> accounts = jdbcTemplate.query("select * from bankAccount where name = ?",
new BeanPropertyRowMapper<Account>(Account.class),
name);
if (accounts.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
} public void update(Account account) {
jdbcTemplate.update("update bankAccount set name = ?, money = ? where id = ?",
account.getName(), account.getMoney(), account.getId());
}
}

账户的持久层接口的实现类:AccountServiceImpl.java

package cn.parzulpan.service;

import cn.parzulpan.dao.AccountDAO;
import cn.parzulpan.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; /**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 账户的业务层接口的实现类,事务控制应该在业务层
*/ @Service("accountService")
public class AccountServiceImpl implements AccountService {
@Resource(name = "accountDAO")
private AccountDAO accountDAO; @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Account findById(Integer accountId) {
return accountDAO.findById(accountId);
} @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void transfer(String sourceName, String targetName, Double money) {
System.out.println("开始进行转账..."); Account source = accountDAO.findByName(sourceName);
Account target = accountDAO.findByName(targetName);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDAO.update(source);
int i = 1 / 0; // 模拟转账故障
accountDAO.update(target); System.out.println("转账完成...");
}
}

配置文件:bean.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="cn.parzulpan"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springT?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean> <!-- 1. 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 2. 开启对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <!-- 3. 在需要事务支持的地方使用 @Transactional -->
</beans>

总结和练习

【Spring】Spring 事务控制的更多相关文章

  1. 13 Spring 的事务控制

    1.事务的概念 理解事务之前,先讲一个你日常生活中最常干的事:取钱.  比如你去ATM机取1000块钱,大体有两个步骤:首先输入密码金额,银行卡扣掉1000元钱:然后ATM出1000元钱.这两个步骤必 ...

  2. 04 Spring:01.Spring框架简介&&02.程序间耦合&&03.Spring的 IOC 和 DI&&08.面向切面编程 AOP&&10.Spring中事务控制

    spring共四天 第一天:spring框架的概述以及spring中基于XML的IOC配置 第二天:spring中基于注解的IOC和ioc的案例 第三天:spring中的aop和基于XML以及注解的A ...

  3. spring的事务控制

    1.事务介绍 (1)特性:ACID Atomicity(原子性):事务中的所有操作要么全做要么全不做 Consistency(一致性):事务执行的结果使得数据库从一个一致性状态转移到另一个一致性状态 ...

  4. 阶段3 2.Spring_10.Spring中事务控制_9 spring编程式事务控制1-了解

    编程式的事物控制,使用的情况非常少,主要作为了解 新建项目 首先导入包坐标 复制代码 这里默认值配置了Service.dao和连接池其他的内容都没有配置 也就说现在是没有事物支持的.运行测试文件 有错 ...

  5. 阶段3 2.Spring_10.Spring中事务控制_8 spring基于纯注解的声明式事务控制

    新建项目 把之前项目src下的内容全部复制过来 pom.xml内复制过来 开始配置 新建一个config的包,然后再新建配置文件类SpringConfiguration @Configuration这 ...

  6. 阶段3 2.Spring_10.Spring中事务控制_6 spring基于XML的声明式事务控制-配置步骤

    环境搭建 新建工程 把对应的依赖复制过来 src下内容复制 配置spring中的声明事物 找到bean.xml开始配置 配置事物管理器 里面需要注入DataSource 2-配置事物通知 需要先导入事 ...

  7. 阶段3 2.Spring_10.Spring中事务控制_5 spring事务控制的代码准备

    创建一个工程,只搭建环境不做配置.等配置的时候把这个项目相关的代码再复制到新项目里面 jar包的打包方式 导入包 事务控制也是基于AOP的.所以这里导入aspectjweaver 复制jdbcTemp ...

  8. 阶段3 2.Spring_10.Spring中事务控制_4 spring中事务控制的一组API

    分析aop的 xml 的代码.更直观一些 事务提交和回滚就是我们重复的代码 spring业余事务管理器,我们拿过来直接用就可以 提交和回滚的后面直接调用释放.所以释放资源之类就是多余的 在绑定连接到线 ...

  9. 阶段3 2.Spring_10.Spring中事务控制_1 基于XML的AOP实现事务控制

    新建项目 首先把依赖复制进来 aop必须引入.aspectjweaver 复制src下的所有内容 复制到我们的新项目里面 factory文件夹删掉 删除后测试类必然就报错 配置文件 beanFacto ...

  10. Spring的事务控制-基于注解的方式

    模拟转账操作,即Jone减少500,tom增加500 如果有疑问请访问spring事务控制-基于xml方式 1.创建数据表 2.创建Account实体类 public class Account { ...

随机推荐

  1. stringbuilder和stringbuffer速度比较

    同样的代码,只改了类型,分别为stringbuilder和stringbuffer,只比较一下,执行引擎为hive. 当数据量为100000条,string builder耗时280秒,stringb ...

  2. Python编码相关

    1.#coding=utf-8的作用 作用是这个文件代码的编码格式,如果没有声明代码中不能出现中文字符,包括注释中也不能出现.否则会报错SyntaxError: Non-ASCII character ...

  3. .NET5下的三维应用程序开发

    终于等到了.NET5的发布,怀着激动的心情体验了一下:"香"就一个字. 如何基于.NET5开发工业软件,也广大三维应用开发者关心的问题.我们的Rapid SDK已经率先支持.NET ...

  4. .NET Core +Angular 项目 部署到CentOS

    前言: 最近公司需要开发项目能在Linux系统上运行,示例开发项目采用.Net Core + Angular开发:理论上完全支持跨平台. 但是实践才是检验真理的唯一标准:那么还是动手来验证实现下:过程 ...

  5. 如何配置nginx达到只允许域名访问网址,禁止ip访问的效果

    需求:接入阿里云的waf对网站进行防护,但是如果直接通过IP地址访问网站即可绕过阿里云waf,于是希望禁止通过ip访问网站 修改nginx配置文件 在server段里插入如下内容即可 if ($hos ...

  6. 自顶向下redis4.0(4)时间事件与expire

    redis4.0的时间事件与expire 目录 redis4.0的时间事件与expire 简介 正文 时间事件注册 时间事件触发 expire命令 删除过期键值 被动删除 主动删除/定期删除 参考文献 ...

  7. tp5使用PHPWord(下载引入/composer两种方式)

    PHPWORD使用文档 一:引入 tp5.0,tp5.1: 1:composer方式(推荐) a:根目录下执行:composer require phpoffice/phpword b:引入: use ...

  8. html 04-HTML标签图文详解(一)

    04-HTML标签图文详解(一) #一.排版标签 #注释标签 <!-- 注释 -->   #段落标签<p> <p>This is a paragraph</p ...

  9. css 07-浮动

    07-浮动.md #文本主要内容 标准文档流 标准文档流的特性 行内元素和块级元素 行内元素和块级元素的相互转换 浮动的性质 浮动的清除 浏览器的兼容性问题 浮动中margin相关 关于margin的 ...

  10. 抢先看:笔者亲历的2020年中国.NET开发者大会活动纪实

    2020年中国.NET开发者大会活动纪实 1 2020年12月19日的苏州工业园区,天公作美,阳光明媚,气象迷人,正是一个搞事的好日子.在这里,数百名中国.NET开发者们汇聚一堂,怀揣着激情和梦想,一 ...