一、事务概念
1、什么是事务

2、事务四个特性(ACID)
(1)原子性 (2)一致性 (3)隔离性 (4)持久性
二、搭建事务操作环境
1、转账操作演示
示例图说明

① 创建数据库表,添加记录

② 创建 service,搭建 dao,完成对象创建和注入关系
Service层:
Dao层注入说明:
③ 在 dao 创建两个方法:多钱和少钱的方法,在 service 创建方法(转账的方法)
说明:创建两个方法分别执行两个账户的操作,一个是Tom减去100,另一个是Lily增加100
package com.mjj.Spring5.dao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository;/*** @anthor changlu* @create 2020-08-18-16:30*/@Repositorypublic class UserDaoImpl implements UserDao{@Autowiredprivate JdbcTemplate jdbcTemplate;@Overridepublic void transferToLily() {//Tom的账户金额减少100元String sql = "update t_account set money=money-? where name = ?";int status = jdbcTemplate.update(sql, 100, "Tom");System.out.println(status);//输出执行的状态}@Overridepublic void lilyGetMoney() {//Lily的账户获得100元String sql = "update t_account set money=money+? where name = ?";int status = jdbcTemplate.update(sql, 100, "Lily");System.out.println(status);//输出执行的状态}}
④ service层调用以及进行测试
说明:service层调用DAO层两个方法进行转账实现
package com.mjj.Spring5.service;import com.mjj.Spring5.dao.UserDao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;/*** @anthor changlu* @create 2020-08-18-16:29*/@Servicepublic class UserService {@Autowiredprivate UserDao userDao;//进行转账业务public void transferAccount(){//下面执行两个操作Tom账户-100,Lily账户+100userDao.transferToLily();userDao.lilyGetMoney();}}
进行测试:使用IOC进行获取对象来调用方法
package com.mjj.Spring5.test;import com.mjj.Spring5.service.UserService;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @anthor changlu* @create 2020-08-18-16:30*/public class UserTest {@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");UserService userService = context.getBean("userService", UserService.class);//执行业务层的方法userService.transferAccount();}}
运行结果:
2、出现异常情况的引出
引出情况
出现异常报错,之后的获取金额操作未能执行
测试结果:
执行上面的service方法,在出现异常后,转账未能够完全执行,数据库中操作更改有误
解决方案
说明:在业务层上管进行添加事务
三、Spring 事务管理介绍
1、概述说明(添加到业务层+两种方式管理事务)

说明:**编程式事务就像之前web项目中的添加事务一样,与上面解决方案类似使用代码编程进行解决。**
2、声明式事务管理(注解或xml配置)
① 底层使用
在 Spring 进行声明式事务管理,底层使用 AOP 原理
② Spring 事务管理 API
提供一个接口PlatformTransactionManager,代表事务管理器,这个接口针对不同的框架提供不同的实现类 
我们需要使用DataSourceTransactionManager这个实现类
四、事务操作
1、声明式事务管理(注解方式)
(1) 在 spring 配置文件配置事务管理器
说明:这里需要配置bean实例并且配置数据源dataSource
<!--创建事务管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--为dataSource进行配置,注入数据源--><property name="dataSource" ref="dataSource"></property></bean>
DataSourceTransactionManager类查看:其中包含set方法
(2) 在 spring 配置文件,开启事务注解
① 在 spring 配置文件引入名称空间 tx
<?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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
具体查看下方:
② 开启事务注解(使用到tx名称空间)
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
说明:这里需要使用到上方配置的事务管理器与transaction-manager连用
具体如下:
(3) 在 service 类上面(或者 service 类里面方法上面)添加事务注解
注解写于类与方法上的不同:作用域不同,类是包括整个类中内容,方法上就只针对于方法
事务注解:@Transactional
package com.mjj.Spring5.service;
import com.mjj.Spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @anthor changlu
* @create 2020-08-18-16:29
*/
@Service
@Transactional //为整个类添加事务注解
public class UserService {
@Autowired
private UserDao userDao;
//进行转账业务
public void transferAccount(){
//下面执行两个操作Tom账户-100,Lily账户+100
userDao.transferToLily();
int i = 10/0;
userDao.lilyGetMoney();
}
}
具体如下:
此时再次测试,如果中途异常则会进行回滚操作。
整体步骤说明
① 配置事务管理器
② 开启事务注解
③ 在类或方法上引入注解
2、声明式事务管理参数配置(注解@Transactional,配置相关参数)
相关参数汇总介绍(主要6个介绍)

各个配置说明
① propagation:事务传播行为(七钟传播行为+介绍前两种)
七种传播行为介绍:
主要两种说明:
实际使用
说明:对于第一个REQUIRED默认就是这个,也可以进行手动添加
② ioslation:事务隔离级别(问题+解决)
问题描述:
脏读
不可重复读:一个未提交事务读取到另一提交事务修改数据 
虚读:一个未提交事务读取到另一提交事务添加数据
解决方法:
设置可重复读:isolation = Isolation.REPEATABLE_READ
③ timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是 -1 ,设置时间以秒单位进行计算
如下图配置:
④ readOnly:是否只读
(1)读:查询操作,写:添加修改删除操作
(2)readOnly 默认值 false,表示可以查询,可以添加修改删除操作
(3)设置 readOnly 值是 true,设置成 true 之后,只能查询
如下图配置:
⑥ rollbackFor与noRollbackFor:设置哪些是否回滚或不回滚

3、声明式事务管理(xml配置)
<!--1 创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--为dataSource进行配置,注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2 配置事务通知-->
<tx:advice id="txadvice">
<!--配置事务参数-->
<tx:attributes>
<!-- 指定哪种规则的方法上面 添加事务 -->
<tx:method name="transferAccount" propagation="REQUIRED"/>
<!--<tx:method name="account*"/> 也可以这种方式命名-->
</tx:attributes>
</tx:advice>
<!--3 配置切入点与切入面-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="pt" expression="execution(* com.mjj.Spring5.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
三步骤说明
大致三步骤示例图:
五、完全注解声明式事务管理
配置类的使用
说明:
① 首先使用注解来声明配置类,开启组件扫描以及开启事务
② 创建三个bean类,一个是德鲁伊数据源,一个是JdbcTemplate,另一个是事务管理器
后两个都需要配置德鲁伊数据源,使用set方法配置,可以通过传参的方式来传入dataSource数据源,在配置类中,会通过IOC来查找对应匹配的bean进行传入来达到配置数据源的方法
package com.mjj.Spring5.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @anthor changlu
* @create 2020-08-19-16:10
*/
@Configuration //配置类
@ComponentScan(basePackages = "com.mjj.Spring5") //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
//创建数据库连接池
@Bean
public DruidDataSource getDruidDataSource(){
//创建德鲁伊数据源
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user_db");
dataSource.setUsername("root");
dataSource.setPassword("123456");
return dataSource;
}
//创建JdbcTemplate对象
@Bean
public JdbcTemplate getJdbcTemplate(DruidDataSource dataSource){//这里可以根据IOC容器中找到对应bean来获取到
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);//这里根据参数获取,参数根据IOC容器中获取
return jdbcTemplate;
}
//创建事务管理器
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DruidDataSource dataSource){//这里从IOC中自动获取到
//创建事务管理器
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
//注入数据源
transactionManager .setDataSource(dataSource);
return transactionManager ;
}
}
测试使用配置类
说明:对于完全注解的形式来创建配置类,就需要使用ApplicationContext的另一个实现类AnnotationConfigApplicationContext(class),传入对应配置类的class类即可。
之前对应读入配置文件是使用ClassPathXmlApplicationContext
@Test
public void test1(){
//这里使用到AnnotationConfigApplicationContext这个类,通过输入对应配置类的class作为参数传入
ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
UserService userService = context.getBean("userService", UserService.class);
//执行业务层的方法
userService.transferAccount();
}
整理者:长路 时间:2020/8/18
