事务操作(Spring事务管理)

28 阅读2分钟

Spring事务管理介绍

1、事务添加到JavaEE三层结构的Service层(业务逻辑层)
2、在Spring中进行事务管理操作
有两种方式:

  • 编程式事务管理
  • 声明式事务管理(常用)

3、声明式事务管理
(1)基于注解方式
(2)基于xml配置文件方式
4、在Spring进行声明式事务管理,底层使用AOP原理
5、Spring事务管理API
提供接口,代表事务管理器,这个接口针对不同的框架提供了不同的实现类

事务操作(注解声明式事务管理)

1、在spring配置文件配置事务管理器

    <!-- 创建事务管理器  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--        注入数据源-->

2、在spring配置文件,开启事务注解
(1)在spring配置文件引入名称空间tx

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

(2)创建事务管理器,注入数据源

<!-- 创建事务管理器  -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"></property>
</bean>

(3)开启事务注解

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

3、在service类上面(获取service类里面方法上面)添加事务注解
(1)@Transactional :这个注解添加到类上面,也可以添加到方法上面
(2)如果把这个注解添加到类上面,这个类里面的所有的方法都添加上了事务
(3)如果把这个注解添加到方法上面,就只是为这个方法添加了事务

@Service
@Transactional
public class BookService {

4、propagation:事务传播行为
当一个事务方法被另一个事务方法调用时,这个事务方法如何进行

5、事务隔离级别
(1)事务有一个特性,称为隔离性,即多事务操作之间不会产生影响。不考虑隔离性,就会产生很多问题。

  • 有三个读问题:脏读,不可重复读,虚读
  • 脏读:一个未提交事务读取到了另一个未提交事务的数据
  • 不可重复读:一个未提交事务读取到了另一个提交事务的修改数据
  • 虚读:一个未提交事务读取到了另一个提交事务的添加数据

(2)通过设置事务隔离级别,解决读问题

6、事务操作(完全注解声明式事务管理)