Spring 事物

1.1  回顾事务

l  事务:一组业务操作ABCD,要么全部成功,要么全部不成功。

l  特性:ACID

       原子性:整体

       一致性:完成

       隔离性:并发

       持久性:结果

l  隔离问题:

       脏读:一个事务读到另一个事务没有提交的数据

       不可重复读:一个事务读到另一个事务已提交的数据(update)

       虚读(幻读):一个事务读到另一个事务已提交的数据(insert)

l  隔离级别:

       readuncommitted:读未提交。存在3个问题

       readcommitted:读已提交。解决脏读,存在2个问题

       repeatableread:可重复读。解决:脏读、不可重复读,存在1个问题。

       serializable:串行化。都解决,单事务。

      

l  mysql 事务操作--简单

ABCD 一个事务

Connection conn = null;

try{

  //1 获得连接

  conn = ...;

  //2 开启事务

  conn.setAutoCommit(false);

  A

  B

  C

  D

  //3 提交事务

  conn.commit();

} catche(){

  //4 回滚事务

  conn.rollback();

}

 

l  mysql 事务操作--Savepoint

需求:AB(必须),CD(可选)

Connection conn = null;

Savepoint savepoint = null;  //保存点,记录操作的当前位置,之后可以回滚到指定的位置。(可以回滚一部分)

try{

  //1 获得连接

  conn = ...;

  //2 开启事务

  conn.setAutoCommit(false);

  A

  B

  savepoint = conn.setSavepoint();

  C

  D

  //3 提交事务

  conn.commit();

} catche(){

  if(savepoint != null){   //CD异常

     // 回滚到CD之前

     conn.rollback(savepoint);

     // 提交AB

     conn.commit();

  } else{   //AB异常

     // 回滚AB

     conn.rollback();

  }

}

 

1.2  事务管理介绍

1.2.1   导入jar包

transaction -->  tx

 

1.2.2   三个顶级接口

l  PlatformTransactionManager  平台事务管理器,spring要管理事务,必须使用事务管理器

       进行事务配置时,必须配置事务管理器

l  TransactionDefinition:事务详情(事务定义、事务属性),spring用于确定事务具体详情,

       例如:隔离级别、是否只读、超时时间 等

       进行事务配置时,必须配置详情。spring将配置项封装到该对象实例。

l  TransactionStatus:事务状态,spring用于记录当前事务运行状态。例如:是否有保存点,事务是否完成。

       spring底层根据状态进行相应操作。

 

1.2.3   PlatformTransactionManager  事务管理器

l  导入jar包:需要时平台事务管理器的实现类

      

 

l  常见的事务管理器

       DataSourceTransactionManager  jdbc开发时事务管理器,采用JdbcTemplate

       HibernateTransactionManagerhibernate时事务管理器,整合hibernate

 

l  api详解

TransactionStatus getTransaction(TransactionDefinition definition) ,事务管理器通过“事务详情”,获得“事务状态”,从而管理事务。

void commit(TransactionStatus status)  根据状态提交

void rollback(TransactionStatus status) 根据状态回滚

 

1.2.4   TransactionStatus

 

 

1.2.5   TransactionDefinition

l  传播行为:在两个业务之间如何共享事务。

 

PROPAGATION_REQUIRED , required , 必须 【默认值】

       支持当前事务,A如果有事务,B将使用该事务。

       如果A没有事务,B将创建一个新的事务。

PROPAGATION_SUPPORTS ,supports ,支持

       支持当前事务,A如果有事务,B将使用该事务。

       如果A没有事务,B将以非事务执行。

PROPAGATION_MANDATORY,mandatory ,强制

       支持当前事务,A如果有事务,B将使用该事务。

       如果A没有事务,B将抛异常。

PROPAGATION_REQUIRES_NEW , requires_new ,必须新的

       如果A有事务,将A的事务挂起,B创建一个新的事务

       如果A没有事务,B创建一个新的事务

PROPAGATION_NOT_SUPPORTED ,not_supported ,不支持

       如果A有事务,将A的事务挂起,B将以非事务执行

       如果A没有事务,B将以非事务执行

PROPAGATION_NEVER ,never,从不

       如果A有事务,B将抛异常

       如果A没有事务,B将以非事务执行

PROPAGATION_NESTED ,nested ,嵌套

       A和B底层采用保存点机制,形成嵌套事务。

 

掌握:PROPAGATION_REQUIREDPROPAGATION_REQUIRES_NEWPROPAGATION_NESTED

 

ServiceA#methodA(我们称之为外部事务),ServiceB#methodB(我们称之为内部事务)
 
[java]  view plain  copy
  1. ServiceA {  
  2.          
  3.      void methodA() {  
  4.          ServiceB.methodB();  
  5.      }  
  6.     
  7. }  
  8.     
  9. ServiceB {  
  10.          
  11.      void methodB() {  
  12.      }  
  13.          
  14. }  

PROPAGATION_REQUIRED

假如当前正要执行的事务不在另外一个事务里,那么就起一个新的事务 
比如说,ServiceB.methodB的事务级别定义为PROPAGATION_REQUIRED, 那么由于执行ServiceA.methodA的时候
  1、如果ServiceA.methodA已经起了事务,这时调用ServiceB.methodB,ServiceB.methodB看到自己已经运行在ServiceA.methodA的事务内部,就不再起新的事务。这时只有外部事务并且他们是共用的,所以这时ServiceA.methodA或者ServiceB.methodB无论哪个发生异常methodA和methodB作为一个整体都将一起回滚。
  2、如果ServiceA.methodA没有事务,ServiceB.methodB就会为自己分配一个事务。这样,在ServiceA.methodA中是没有事务控制的。只是在ServiceB.methodB内的任何地方出现异常,ServiceB.methodB将会被回滚,不会引起ServiceA.methodA的回滚

 

PROPAGATION_REQUIRES_NEW

启动一个新的, 不依赖于环境的 "内部" 事务. 这个事务将被完全 commited 或 rolled back 而不依赖于外部事务, 它拥有自己的隔离范围, 自己的锁, 等等. 当内部事务开始执行时, 外部事务将被挂起, 内务事务结束时, 外部事务将继续执行. 
 比如我们设计ServiceA.methodA的事务级别为PROPAGATION_REQUIRED,ServiceB.methodB的事务级别为PROPAGATION_REQUIRES_NEW,那么当执行到ServiceB.methodB的时候,ServiceA.methodA所在的事务就会挂起,ServiceB.methodB会起一个新的事务,等待ServiceB.methodB的事务完成以后,他才继续执行。他与PROPAGATION_REQUIRED 的事务区别在于事务的回滚程度了。因为ServiceB.methodB是新起一个事务,那么就是存在两个不同的事务。
1、如果ServiceB.methodB已经提交,那么ServiceA.methodA失败回滚,ServiceB.methodB是不会回滚的
2、如果ServiceB.methodB失败回滚,如果他抛出的异常被ServiceA.methodA的try..catch捕获并处理,ServiceA.methodA事务仍然可能提交;如果他抛出的异常未被ServiceA.methodA捕获处理,ServiceA.methodA事务将回滚。

PROPAGATION_NESTED

开始一个 "嵌套的" 事务,  它是已经存在事务的一个真正的子事务. 嵌套事务开始执行时,  它将取得一个 savepoint. 如果这个嵌套事务失败, 我们将回滚到此 savepoint. 嵌套事务是外部事务的一部分, 只有外部事务结束后它才会被提交. 

比如我们设计ServiceA.methodA的事务级别为PROPAGATION_REQUIRED,ServiceB.methodB的事务级别为PROPAGATION_NESTED,那么当执行到ServiceB.methodB的时候,ServiceA.methodA所在的事务就会挂起,ServiceB.methodB会起一个新的子事务并设置savepoint,等待ServiceB.methodB的事务完成以后,他才继续执行。因为ServiceB.methodB是外部事务的子事务,那么
1、如果ServiceB.methodB已经提交,那么ServiceA.methodA失败回滚,ServiceB.methodB也将回滚。
2、如果ServiceB.methodB失败回滚,如果他抛出的异常被ServiceA.methodA的try..catch捕获并处理,ServiceA.methodA事务仍然可能提交;如果他抛出的异常未被ServiceA.methodA捕获处理,ServiceA.methodA事务将回滚。

理解Nested的关键是savepoint。他与PROPAGATION_REQUIRES_NEW的区别是:
PROPAGATION_REQUIRES_NEW 完全是一个新的事务,它与外部事务相互独立; 而 PROPAGATION_NESTED 则是外部事务的子事务, 如果外部事务 commit, 嵌套事务也会被 commit, 这个规则同样适用于 roll back. 

 

1.3  案例:转账

1.3.1   搭建环境

1.3.1.1        创建表

create database ee19_spring_day03;

use ee19_spring_day03;

create table account(

  id int primary key auto_increment,

  username varchar(50),

  money int

);

insert into account(username,money) values('jack','10000');

insert into account(username,money) values('rose','10000');

 

1.3.1.2        导入jar包

l  核心:4+1

l  aop : 4 (aop联盟、spring aop、aspectj规范、spring aspect)

l  数据库:2  (jdbc/tx)

l  驱动:mysql

l  连接池:c3p0

 

 

1.3.1.3        dao层

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

 

   @Override

   public void out(String outer, Integer money) {

      this.getJdbcTemplate().update("update account set money = money - ? where username = ?", money,outer);

   }

 

   @Override

   public void in(String inner, Integer money) {

      this.getJdbcTemplate().update("update account set money = money + ? where username = ?", money,inner);

   }

 

}

 

1.3.1.4        service层

public class AccountServiceImpl implements AccountService {

 

   private AccountDao accountDao;

   public void setAccountDao(AccountDao accountDao) {

      this.accountDao = accountDao;

   }

   @Override

   public void transfer(String outer, String inner, Integer money) {

      accountDao.out(outer, money);

      //断电

//    int i = 1/0;

      accountDao.in(inner, money);

   }

 

}

 

 

1.3.1.5        spring配置

    <!-- 1 datasource -->

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>

        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ee19_spring_day03"></property>

        <property name="user" value="root"></property>

        <property name="password" value="1234"></property>

    </bean>

   

    <!-- 2 dao  -->

    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">

        <property name="dataSource" ref="dataSource"></property>

    </bean>

    <!-- 3 service -->

    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">

        <property name="accountDao" ref="accountDao"></property>

    </bean>

 

1.3.1.6        测试

    @Test

    public void demo01(){

        String xmlPath = "applicationContext.xml";

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);

        AccountService accountService =  (AccountService) applicationContext.getBean("accountService");

        accountService.transfer("jack", "rose", 1000);

    }

 

1.3.4   AOP 配置基于xml【掌握】

l  在spring xml 配置aop 自动生成代理,进行事务的管理

1.配置管理器

2.配置事务详情

3.配置aop

 

<!-- 4 事务管理 -->

    <!-- 4.1 事务管理器 -->

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource"></property>

    </bean>

    <!-- 4.2 事务详情(事务通知)  aop筛选基础上,对ABC三个确定使用什么样的事务。例如:AC读写、B只读

        <tx:attributes> 用于配置事务详情(属性属性)

            <tx:method name=""/> 详情具体配置

                propagation 传播行为 REQUIRED:必须;REQUIRES_NEW:必须是新的

                isolation 隔离级别

    -->

    <tx:advice id="txAdvice" transaction-manager="txManager">

        <tx:attributes>

            <tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT"/>

        </tx:attributes>

    </tx:advice>

    <!-- 4.3 AOP编程,目标类有ABCD4个连接点),切入点表达式确定增强的连接器,从而获得切入点:ABC -->

    <aop:config>

        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service..*.*(..))"/>

    </aop:config>

 

 

1.3.5   AOP配置基于注解【掌握】

l  1.配置事务管理器,将并事务管理器交予spring

l  2.在目标类或目标方法添加注解即可 @Transactional

 

 

1.3.5.1        spring配置

<!-- 4 事务管理 -->

    <!-- 4.1 事务管理器 -->

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource"></property>

    </bean>

    <!-- 4.2 将管理器交予spring

        * transaction-manager 配置事务管理器

        * proxy-target-class

            true 底层强制使用cglib代理

    -->

    <tx:annotation-driven transaction-manager="txManager"/>

 

1.3.5.2        service 层

@Transactional

public class AccountServiceImpl implements AccountService {

 

1.3.5.3        事务详情配置

 

@Transactional(propagation=Propagation.REQUIRED , isolation = Isolation.DEFAULT)

public class AccountServiceImpl implements AccountService {

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值