文章目录
前言
跟随尚硅谷学习Spring5
事务操作(事务概念)
一、事务(概念和准备)
- 什么事务
- 事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败
- 典型场景:银行转账
lucy转账100元给mary
lucy少100,mary多 100
- 事务四个特性(ACID)
- 原子性
- 一致性
- 隔离性
- 持久性
二、事务操作(搭建事务操作环境)
Service中写业务操作:创建转账的方法,调用dao两个的方法
Dao中写数据库操作不写业务:创建两个方法-少钱的方法-多钱的方法
创建数据库表,添加记录
创建 service,搭建 dao,完成对象创建和注入关系
service 注入 dao,在 dao 注入 JdbcTemplate,在 JdbcTemplate 注入 DataSource
package com.atguigu.spring5.transanctional.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
}
package com.atguigu.spring5.transanctional.service;
import com.atguigu.spring5.transanctional.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
// 注入dao
@Autowired
private UserDao userDao;
}
在 dao 创建两个方法:多钱和少钱的方法,在 service 创建方法(转账的方法)
package com.atguigu.spring5.transanctional.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
// 多钱的方法: Mary收到Lucy转过来的100
public void addMoney() {
String sql = "UPDATE t_accounts SET money=money+? where username=?";
jdbcTemplate.update(sql, 100, "Mary");
}
// 少钱的方法: Lucy转账100给Mary
public void reduceMoney() {
String sql = "UPDATE t_accounts SET money=money-? where username=?";
jdbcTemplate.update(sql, 100, "Lucy");
}
}
测试:
package com.atguigu.sprint5;
import com.atguigu.spring5.transanctional.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestTransactional {
@Test
public void testTransactional() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-jdbctemplate.xml");
UserService userService = context.getBean("userService", UserService.class);
// 完成转账的方法测试
userService.moveMoney();
}
}
异常处理:
public void accountMoney(){
try{
//第一步开启事务
//第二步进行业务操作
//lucy少100
userDao.reduceMoney();
//模拟异常
int i = 10/0;
//mary多100
userDao.addMoney();
//第三步没有发生异常,提交事务
} catch(Exception e)
//第四步出现异常,事务回滚
}
}
三、事务操作(Spring 事务管理介绍)
- 事务添加到 JavaEE 三层结构里面 Service 层(业务逻辑层)
- 在 Spring 进行事务管理操作
- 有两种方式: 编程式事务管理和声明式事务管理(使用)
- 声明式事务管理
- 基于注解方式(使用)
- 基于 xml 配置文件方式
- 在 Spring 进行声明式事务管理,底层使用 AOP 原理
- Spring 事务管理 API
- 提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类
DataSourceTransactionManager(org.springframework.jdbc.datasource)
四、事务操作(注解声明式事务管理)
在 spring 配置文件配置事务管理器
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
在 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:aop="http://www.springframework.org/schema/aop"
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/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
开启事务注解
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
在 service 类上面( 或者 service 类里面方法上面)添加事务注解
@Transactional,这个注解添加到类上面,也可以添加方法上面
如果把这个注解添加类上面,这个类里面所有的方法都添加事务
如果把这个注解添加方法上面,为这个方法添加事务
@Service
@Transactional
public class UserService
五、事务操作(声明式事务管理参数配置)
- 在 service 类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数
- propagation:事务传播行为
当一个事务方法被另外一个事务方法调用时候,这个事务方法如何进行
传播属性 | 描述 |
---|---|
REQUIRED | 如果有事务在运行,当前的方法就在这个事务内运行,否则,就用动一个新的事务,并在自己的事务内运行 |
REQUIRED_NEW | 当前的方法必须启动新事务,并在它自己的事务内运行.如果有事务正在运行,应该将它挂起 |
SUPPORTS | 如果有事务在运行,当前的方法就在这个事务内运行.否则它可以不运行在事务中 |
NO_SUPPORTED | 当前的方法不应该运行在事务中.如果有运行的事务,将它挂起 |
MANDATORY | 当前的方法必须运行在事务内部,如果没有正在运行的事务,就抛出异常 |
NEVER | 当前的方法不应该运行在事务中.如果有运行的事务,就抛出异常 |
NESTED | 如果有事务在运行,当前的方法就应该在这个事务的嵌套事务内运行.否则,就启动一个新的事务,并在它自己的事务内运行 |
- ioslation:事务隔离级别
- 事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
- 有三个读问题:脏读、不可重复读、虚(幻)读
- 脏读:一个未提交事务读取到另一个未提交事务的数据
- 不可重复读:一个未提交事务读取到另一提交事务修改数据
- 一个未提交事务读取到另一提交事务添加数据
- 解决: 通过设置事务隔离级别,解决读问题
隔离级别 | 脏读 | 不可重复读 | 幻读 |
---|---|---|---|
READ UNCOMMITTED(读未提交) | 有 | 有 | 有 |
READ COMMITTED(读已提交) | 无 | 有 | 有 |
REPEATABLE READ(可重复读) | 无 | 无 | 有 |
SERIALIZABLE(串行化) | 无 | 无 | 无 |
- timeout:超时时间
- 事务需要在一定时间内进行提交,如果不提交进行回滚
- 默认值是-1,设置时间以秒单位进行计算
- readOnly:是否只读
- 读:查询操作,写:添加修改删除操作
- readOnly 默认值 false,表示可以查询,可以添加修改删除操作
- 设置readOnly值是true,设置成true之后,只能查询
- rollbackFor:回滚
- 设置出现哪些异常进行事务回滚
- noRollbackFor:不回滚
- 设置出现哪些异常不进行事务回滚
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, timeout = -1, readOnly = false) // 多个默认值一起写的写法
六、事务操作( XML 声明式事务管理)
在 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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.atguigu.spring5.transanctionalXml"/>
<!--数据库连接池-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置JdbcTemplate对象,注入DataSource-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--1 创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--2 配置通知-->
<tx:advice id="txadvice">
<tx:attributes>
<!--Option1:指定具体某个方法添加事务-->
<tx:method name="moveMoney" propagation="REQUIRED" isolation="REPEATABLE_READ" timeout="-1"/>
<!--Option2: 正则匹配方法添加事务-->
<!-- <tx:method name="move*"/>-->
</tx:attributes>
</tx:advice>
<!--3 配置切入点和切面-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="pt" expression="execution(* com.atguigu.spring5.transanctionalXml.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
</beans>
七、事务操作(完全注解声明式事务管理)
创建配置类,使用配置类替代 xml 配置文件
package com.atguigu.spring5.transanctionalFullAnnotations.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;
import javax.sql.DataSource;
@Configuration
@ComponentScan(basePackages = "com.atguigu.spring5.transanctionalFullAnnotations") //组建扫描
@EnableTransactionManagement //开启事务
public class SpringTxConfig {
//创建数据库连接池
@Bean
public DruidDataSource getDruidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring_book?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
druidDataSource.setUsername("root");
druidDataSource.setPassword("123456");
return druidDataSource;
}
//创建JdbcTemplate对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//传入创建的DataSource:到ioc容器中根据类型找到dataSource,这里不直接调用get方法了
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//创建事务管理器
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
测试:
package com.atguigu.spring5.transanctionalFullAnnotations;
import com.atguigu.spring5.transanctionalFullAnnotations.config.SpringTxConfig;
import com.atguigu.spring5.transanctionalFullAnnotations.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestTransactionalFullAnnotations {
@Test
public void testTransactionalFullAnnotations() {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringTxConfig.class);
UserService userService = context.getBean("userService", UserService.class);
// 完成转账的方法测试
userService.moveMoney();
}
}