Spring事务管理详细讲解

发布时间:

事务是逻辑上的一组数据库操作,要么都执行,要么都不执行。

假如,张三给李四转账100元,转账行为欧两个关键操作:将张三的余额减200元,将李四的余额增加200元。如果两个操作之间突然出现错误,例如银行系统崩溃导致张三余额减少,而李四的余额没有增加,这样的系统是有问题的。事务就是保证这两个关键操作要么都成功,要么都要失败。

事务的特性:

  • 事务是最小的执行单位,不允许分割。事务的原子性确保动作要么全部完成,要么完全不起作用;
  • 一致性: 确保从一个正确的状态转换到另外一个正确的状态,这就是一致性;
  • 并发访问数据库时,一个用户的事务不被其他事务所干扰,各并发事务之间数据库是独立的;
  • 持久性:一个事务被提交之后,对数据库中数据的改变是持久的,即使数据库发生故障也不应该对其有任何影响。

spring事务操作

在 Spring 进行事务管理操作,编程式事务管理和声明式事务管理。编程式事务管理一般是代码手动控制,比较繁琐,所以一般推荐使用声明式事务管理。

为了讲解事务的机制,以银行在那个转账为例,创建服务类、dao类,如下:

dao接口:

package com.example.dao;
public interface UserDao {
/**
 * 取钱
 */
void reduceMoney();
/**
 * 存钱
 */
void addMoney();
}

dao接口实现类

package com.example.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;
@Override
public void reduceMoney() {
String sql = "update t_account set money=money-? where username=?";
jdbcTemplate.update(sql,100,"lucy");
}
@Override
public void addMoney() {
String sql = "update t_account set money=money+? where username=?";
jdbcTemplate.update(sql,100,"mary");
}
}

service类

package com.example.service;
import com.example.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserDao userDao;
/**
 * 模拟转账操作
 */
public void accountMoney() {
//lucy 少 100
userDao.reduceMoney();
//mary 多 100
userDao.addMoney();
}
}

其中accountMoney方法模拟了转账操作。

基于注解声明事务

在 Spring 进行声明式事务管理,使用注解@Transactional注解,底层使用 AOP 原理。其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,执行完目标方法之后根据执行的情况提交或者回滚。

@Transactional注解使用

下面使用注解@Transactional来模拟银行转账开启事务。

1.配置事务管理器

配置文件如下:

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源--> 
<property name="dataSource" ref="dataSource"></property>
</bean>

2.在 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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>

3.配置文件中开启事务注解

<!--开启事务注解--> 
<tx:annotation-driven transactionmanager="transactionManager"></tx:annotation-driven>

整体的配置文件如下:

<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.example"></context:component-scan>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
  destroy-method="close"> <property name="url" value="jdbc:mysql://localhost:3306/cys-test" />
<property name="username" value="root" />
<property name="password" value="123456" />
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启事务-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

4.在 service 类上面添加事务注解

或者 service 类里面方法上面添加事务注解(@Transactional)。

如果把这个注解添加类上面,这个类里面所有的方法都添加事务,如果把这个注解添加方法上面,为这个方法添加事务。

package com.example.service;
import com.example.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UserService {
@Autowired
private UserDao userDao;
/**
 * 模拟转账操作
 */
public void accountMoney() {
System.out.println("开始转账");
//lucy 少 100
userDao.reduceMoney();
// 模拟中间异常
int i = 10/0;
//mary 多 100
userDao.addMoney();
System.out.println("转账结束");
}
}

其中再转账的过程中使用除数为0的异常来模拟一同出现异常。

5.测试类

package com.example.test;
import com.example.service.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test01 {
@Test
public void testAccount() {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = app.getBean(UserService.class);
userService.accountMoney();
}
}

经过测试结果就是:如果不开启事务,中间出现异常,前面已经执行的操作就会提交到数据库,这样上面的案例的结果就是lucy的钱少了100,但是mary的钱并没有增多。如果开启事务,则lucy的钱少了100和mary的钱加100是一个原子操作,中间出现异常就会把全部操作回滚。

事务传播机制

当事务方法被另外一个事务方法调用时,必须指定事务应该如何传播,例如,方法可能继续在当前事务中执行,也可以开启一个新的事务,在自己的事务中执行。

声明式事务的传播行为可以通过 @Transactional 注解中的 propagation 属性来定义,格式如下:

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class UserService {
}

Propagation属性有如下几个值,其中PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW 两种传播行为是比较常用。

传播行为 描述
PROPAGATION_REQUIRED 默认的Spring事物传播级别,若当前存在事务,则加入该事务,若不存在事务,则新建一个事务
PROPAGATION_REQUIRE_NEW 若当前没有事务,则新建一个事务。若当前存在事务,则新建 一个事务,新老事务相互独立。外部事务抛出异常回滚不会影响内部事务的正常提交
PROPAGATION_NESTED 如果当前存在事务,则嵌套在当前事务中执行。如果当前没有事务, 则新建一个事务,类似于REQUIRE_NEW
PROPAGATION_SUPPORTS 支持当前事务,若当前不存在事务,以非事务的方式执行
PROPAGATION_NOT_SUPPORTED 以非事务的方式执行,若当前存在事务,则把当前事务挂起
PROPAGATION_MANDATORY 强制事务执行,若当前不存在事务,则抛出异常
PROPAGATION_NEVER 以非事务的方式执行,如果当前存在事务,则抛出异常

事务隔离级别

@Transactional 注解中的 isolation 属性来定义事务的隔离级别,有以下五种隔离级别:

  • ISOLATION_DEFAULT,使用数据库默认的隔离级别,MySql 默认采用的是REPEATABLE_READ,也就是可重复读。
  • ISOLATION_READ_UNCOMMITTED,最低的隔离级别,可能会出现脏读、幻读或者不可重复读。
  • ISOLATION_READ_COMMITTED,允许读取并发事务提交的数据,可以防止脏读,但幻读和不可重复读仍然有可能发生。
  • ISOLATION_REPEATABLE_READ,对同一字段的多次读取结果都是一致的,除非数据是被自身事务所修改的,可以阻止脏读和不可重复读,但幻读仍有可能发生。
  • ISOLATION_SERIALIZABLE,最高的隔离级别,虽然可以阻止脏读、幻读和不可重复读,但会严重影响程序性能。

通常情况下,采用默认的隔离级别 ISOLATION_DEFAULT 就可以了,也就是交给数据库来决定。

@Transactional其他属性

1、timeout:超时时间

(1)事务需要在一定时间内进行提交,如果不提交进行回滚

(2)默认值是 -1 ,设置时间以秒单位进行计算

2、readOnly:是否只读

(1)读:查询操作,写:添加修改删除操作

(2)readOnly 默认值 false,表示可以查询,可以添加修改删除操作

(3)设置 readOnly 值是 true,设置成 true 之后,只能查询

3、rollbackFor:回滚

(1)设置出现哪些异常进行事务回滚

4、noRollbackFor:不回滚

(1)设置出现哪些异常不进行事务回滚

基于XML 声明式事务

步骤:

第一步 配置事务管理器

第二步 配置通知

第三步 配置切入点和切面

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"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:aop="http://www.springframework.org/schema/aop"
   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
http://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">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.example"></context:component-scan>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
  destroy-method="close"> <property name="url" value="jdbc:mysql://localhost:3306/cys-test" />
<property name="username" value="root" />
<property name="password" value="123456" />
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--创建事务管理器-->
<bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2 配置通知-->
<tx:advice id="txadvice">
<!--配置事务参数-->
<tx:attributes>
<!--指定哪种规则的方法上面添加事务-->
<tx:method name="accountMoney" propagation="REQUIRED"/>
<!--<tx:method name="account*"/>-->
</tx:attributes>
</tx:advice>
<!--3 配置切入点和切面-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="pt" expression="execution(*com.atguigu.spring5.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
</beans>

完全注解开发

创建配置类,使用配置类替代 xml 配置文件

package com.example.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.example") //组件扫描
@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("root");
return dataSource;
}
//创建 JdbcTemplate 对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
//到 ioc 容器中根据类型找到 dataSource
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入 dataSource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//创建事务管理器
@Bean
public DataSourceTransactionManager
getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new
DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
} }