Spring框架——事务管理

目录

事务的回顾

Spring框架的事务管理相关的类和API

搭建事务管理转账案例的环境(强调:简化开发,以后DAO可以继承JdbcDaoSupport类)

Spring框架的事务管理的分类

Spring框架的事务管理之编程式的事务管理(了解)

Spring框架的事务管理之声明式事务管理,即通过配置文件来完成事务管理(AOP思想)

Spring框架的事务管理之基于AspectJ的XML方式(重点掌握)

Spring框架的事务管理之基于AspectJ的注解方式(重点掌握,最简单的方式)


事务的回顾

1. 事务:指的是逻辑上一组操作,组成这个事务的各个执行单元,要么一起成功,要么一起失败!
2. 事务的特性
    * 原子性:组成这个事务的各个执行单元 不可再分割
    * 一致性:
    * 隔离性:
    * 持久性
​
3. 如果不考虑隔离性,引发安全性问题
    * 读问题:
        * 脏读:一个事务会读取到另一个事务未提交的数据 是不允许的
        * 不可重复读:
        * 虚读:
    
    * 写问题:
        * 丢失更新:
​
4. 如何解决安全性问题
    * 读问题解决,设置数据库隔离级别
    * 写问题解决可以使用 悲观锁和乐观锁的方式解决 

Spring框架的事务管理相关的类和API

1. PlatformTransactionManager接口 -- 平台事务管理器.(真正管理事务的类)。该接口有具体的实现类,根据不同的持久层框架,需要选择不同的实现类!
2. TransactionDefinition接口    -- 事务定义信息.(事务的隔离级别,传播行为,超时,只读)
3. TransactionStatus接口    -- 事务的状态
​
4. 总结:上述对象之间的关系:平台事务管理器真正管理事务对象.根据事务定义的信息TransactionDefinition 进行事务管理,在管理事务中产生一些状态.将状态记录到TransactionStatus中
​
5. PlatformTransactionManager接口中实现类和常用的方法
    1. 接口的实现类
        * 如果使用的Spring的JDBC模板或者MyBatis框架,需要选择DataSourceTransactionManager实现类
        * 如果使用的是Hibernate的框架,需要选择HibernateTransactionManager实现类
    
    2. 该接口的常用方法
        * void commit(TransactionStatus status) 
        * TransactionStatus getTransaction(TransactionDefinition definition) 
        * void rollback(TransactionStatus status) 
    
6. TransactionDefinition 事务定义信息
    1. 事务隔离级别的常量
        * static int ISOLATION_DEFAULT  -- 采用数据库的默认隔离级别
        * static int ISOLATION_READ_UNCOMMITTED 
        * static int ISOLATION_READ_COMMITTED 
        * static int ISOLATION_REPEATABLE_READ 
        * static int ISOLATION_SERIALIZABLE 
        
    2. 事务的传播行为常量(不用设置,使用默认值)
        * 先解释什么是事务的传播行为:解决的是业务层之间的方法调用!!
        
    1. 什么是事务传播行为?
​
事务传播行为用来描述由某一个事务传播行为修饰的方法被嵌套进另一个方法的时事务如何传播。
​
用伪代码说明:
 public void methodA(){
    methodB();
    //doSomething
 }
 
 @Transaction(Propagation=XXX)
 public void methodB(){
    //doSomething
 }
​
代码中`methodA()`方法嵌套调用了`methodB()`方法,`methodB()`的事务传播行为由@Transaction(Propagation=XXX)设置决定。
这里需要注意的methodA()并没有开启事务,某一个事务传播行为修饰的方法并不是必须要在开启事务的外围方法中调用。
        
        * PROPAGATION_REQUIRED(默认值) -- A中有事务,使用A中的事务.如果没有,B就会开启一个新的事务,将A包含进来.(保证A,B在同一个事务中),默认值!!
        * PROPAGATION_SUPPORTS          -- A中有事务,使用A中的事务.如果A中没有事务.那么B也不使用事务.
        * PROPAGATION_MANDATORY         -- A中有事务,使用A中的事务.如果A没有事务.抛出异常.
        
        * PROPAGATION_REQUIRES_NEW(记)-- A中有事务,将A中的事务挂起.B创建一个新的事务.(保证A,B没有在一个事务中)
        * PROPAGATION_NOT_SUPPORTED     -- A中有事务,将A中的事务挂起.
        * PROPAGATION_NEVER             -- A中有事务,抛出异常.
        
        * PROPAGATION_NESTED(记)     -- 嵌套事务.当A执行之后,就会在这个位置设置一个保存点.如果B没有问题.执行通过.如果B出现异常,运行客户根据需求回滚(选择回滚到保存点或者是最初始状态)

搭建事务管理转账案例的环境(强调:简化开发,以后DAO可以继承JdbcDaoSupport类)

1. 步骤一:创建WEB工程,引入需要的jar包
    * IOC的6个包
        com.springsource.org.apache.commons.logging-1.1.1.jar
        com.springsource.org.apache.log4j-1.2.15.jar
        spring-beans-5.0.2.RELEASE.jar
        spring-context-5.0.2.RELEASE.jar
        spring-core-5.0.2.RELEASE.jar
        spring-expression-5.0.2.RELEASE.jar
    * AOP的4个包
         spring-aop-5.0.2.RELEASE.jar
             com.springsource.org.aopalliance-1.0.0.jar
         com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
         spring-aspects-5.0.2.RELEASE.jar
    * C3P0的1个包
        com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
    * MySQL的驱动包
        mysql-connector-java-5.1.7-bin.jar
    * JDBC模板2个包
         spring-jdbc-5.0.2.RELEASE.jar
         spring-tx-5.0.2.RELEASE.jar  事务
    * 整合JUnit测试包
         spring-test-5.0.2.RELEASE.jar
         
    ***如果是Maven工程在pom.xml里面引入jar包的坐标
    
     <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
​
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
​
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
​
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
​
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        
          <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.2.1</version>
        </dependency>
​
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
​
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

​ 2. 步骤二:引入配置文件 ​ * 引入配置文件 ​ * 引入log4j.properties 日志的配置文件 ​ ​ * 引入applicationContext.xml 注意约束要写全了 ​ ​

            <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/tx/spring-tx.xsd">        
                    
                    <!-- 配置C3P0的连接池 -->
            <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="driverClass" value="com.mysql.jdbc.Driver"/>
                <property name="jdbcUrl" value="jdbc:mysql:///spring_test"/>
                <property name="user" value="root"/>
                <property name="password" value="123456"/>
            </bean>
​
                <!-- 配置JDBC的模板类 -->
            <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                <property name="dataSource" ref="dataSource"/>
            </bean>
​
        </beans>
​
3. 步骤三:创建对应的包结构和类
    * org.westos.demo1
        * AccountService
        * AccountServlceImpl
        * AccountDao
        * AccountDaoImpl
​
4. 步骤四:引入Spring的配置文件,将类配置到Spring中
    <bean id="accountService" class="org.westos.demo1.AccountServiceImpl">
    </bean>
    
    <bean id="accountDao" class="org.westos.demo1.AccountDaoImpl">
    </bean>
​
5. 步骤五:在业务层注入DAO ,在DAO中注入JDBC模板(强调:简化开发,以后DAO可以继承JdbcDaoSupport类)
    <bean id="accountService" class="org.westos.demo1.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
    
    <bean id="accountDao" class="org.westos.demo1.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>
​
6. 步骤六:编写DAO和Service中的方法
    public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
        public void outMoney(String out, double money) {
            this.getJdbcTemplate().update("update t_account set money = money - ? where name = ?", money,out);
        }
        public void inMoney(String in, double money) {
            this.getJdbcTemplate().update("update t_account set money = money + ? where name = ?", money,in);
        }
    }
​
7. 步骤七:编写测试程序.
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class Demo1 {
        
        @Resource(name="accountService")
        private AccountService accountService;
        
        @Test
        public void run1(){
            accountService.pay("冠希", "美美", 1000);
        }
    }


Spring框架的事务管理的分类

1. Spring的事务管理的分类
    1. Spring的编程式事务管理(不推荐使用)
        * 通过手动编写代码的方式完成事务的管理(不推荐)
    
    2. Spring的声明式事务管理(底层采用AOP的技术)
        * 通过一段配置的方式完成事务的管理(重点掌握注解的方式)

Spring框架的事务管理之编程式的事务管理(了解)

1. 说明:Spring为了简化事务管理的代码:提供了模板类 TransactionTemplate,所以手动编程的方式来管理事务,
         只需要使用该模板类即可!!
​
2. 手动编程方式的具体步骤如下:
        
    1. 步骤一:配置一个事务管理器,Spring使用PlatformTransactionManager接口来管理事务,所以咱们需要使用到他的实现类!!
        <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!--因为Spring的事务管理器要管理事务,他得拿到数据库连接对象,因为只要连接对象才能提交或回滚事务,
            而连接对象又在C3PO连接池中,所以我们把连接池注入到Spring的事务管理器中,让他帮我们来管理事务. -->
​
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
    2. 步骤二:配置事务管理的模板 如果用手动开启事务,需要配置这个事务管理模板 把平台事务管理器注入进来
        <!-- 配置事务管理的模板 -->
        <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
            <property name="transactionManager" ref="transactionManager"/>
        </bean>
    
    3. 步骤三:在需要进行事务管理的类中,也就是service中,注入事务管理的模板.
        <bean id="accountService" class="org.westos.demo1.AccountServiceImpl">
            <property name="accountDao" ref="accountDao"/>
​
            <property name="transactionTemplate" ref="transactionTemplate"/>
        </bean>
    
    4. 步骤四:在业务层使用模板管理事务:
        // 注入事务模板对象
        private TransactionTemplate transactionTemplate;
        public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
            this.transactionTemplate = transactionTemplate;
        }
        
        public void pay(final String out, final String in, final double money) {
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    // 扣钱
                    accountDao.outMoney(out, money);
                    int a = 10/0;
                    // 加钱
                    accountDao.inMoney(in, money);
                }
            });
        }


Spring框架的事务管理之声明式事务管理,即通过配置文件来完成事务管理(AOP思想)

1. 声明式事务管理又分成两种方式
    * 基于AspectJ的XML方式(重点掌握)
    * 基于AspectJ的注解方式(重点掌握)

Spring框架的事务管理之基于AspectJ的XML方式(重点掌握)

1. 步骤一:恢复转账开发环境 留下C3P0的配置,留下平台事务管理器的配置,留下service dao 这两个类的配置
​
2. 步骤二:引入AOP的开发包
​
3. 步骤三:配置事务管理器
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
​
4. 步骤四:配置事务增强  注意顺序先配置事务增强,再去配置切面 
    <!-- 配置事务增强 关联上事务管理器-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--
                name:绑定事务的方法名,可以使用通配符,可以配置多个。
                isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
                propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
                read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。
                timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
                rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。
                no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
             -->
            <!-- 哪些方法加事务 tx:method 可以出现多个,你可以配置多个方法 方法名也可以通配 比如 pay* -->
            <tx:method name="pay" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
​
5. 步骤五:配置AOP的切面
    <!-- 配置AOP切面产生代理 -->
    <aop:config>
            <aop:advisor advice-ref="txAdvice" pointcut="execution(* org.westos.demo2.AccountServiceImpl.pay(..))"/>
    </aop:config>
    
    * 注意:如果是自己编写的切面,使用<aop:aspect>标签来配置我们写的切面类,如果是Spring框架提供的切面,配置切面类使用<aop:advisor>标签。
​
6. 步骤六:编写测试类
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext2.xml")
    public class Demo2 {
        
        @Resource(name="accountService")
        private AccountService accountService;
        
        @Test
        public void run1(){
            accountService.pay("冠希", "美美", 1000);
        }
    }

Spring框架的事务管理之基于AspectJ的注解方式(重点掌握,最简单的方式)

1. 步骤一:恢复转账的开发环境
​
2. 步骤二:配置事务管理器
    <!-- 配置事务管理器  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
​
3. 步骤三:在配置文件中开启注解事务,把平台事务管理器传进去
    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
​
4. 步骤四:在业务层上添加一个注解:@Transactional
@Transactional 这个注解 加在类上,那么这个类中所有的方法都有事务了
如果加在某个方法上,那这个方法就有事务了,一般我们加在类上
@Transactional 加在方法上这个注解里面里 有一些属性就可以设置,比如 隔离级别,事务的传播行为等等
​
5. 编写测试类
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext3.xml")
    public class Demo3 {
        
        @Resource(name="accountService")
        private AccountService accountService;
        
        @Test
        public void run1(){
            accountService.pay("冠希", "美美", 1000);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jmh-Ethereal

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值