事务概念

  • 事务是数据库操作最基本但愿,逻辑上一组操作要么全部成功,如果有一个失败则全部失败
  • 典型场景,转账

    特性 acid

  • 原子性

  • 一致性
  • 隔离型
  • 持久性

    搭建事务操作环境

    image.png

  • 创建service 创建dao 完成对象创建和注入关系

    • service 中注入 dao ,dao中注入 jdbcTemplate,jdbcTempalte中注入datasource 代码省略 ```java @Repository public class UserDaoImpl implements UserDao { @Autowired private JdbcTemplate jdbcTemplate;

      //lucy 转账 100 给 mary //少钱 @Override public void reduceMoney() {

      1. String sql = "update t_account set money=money-? where username=?";
      2. 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 @Service public class UserService { //注入 dao @Autowired private UserDao userDao;

    //转账的方法
    public void accountMoney() { //lucy 少 100
        userDao.reduceMoney();

//mary 多 100 userDao.addMoney(); } }


- 上面的代码,如果正常执行是没有问题的,但是如果代码执行过程中出现异常,就会出现数据的问题,解决方案就是事务处理

![image.png](https://cdn.nlark.com/yuque/0/2021/png/1608527/1631846124150-fe9722e0-b01f-4dc4-8119-cbf456eaaa76.png#clientId=u4d21e6cd-1ca8-4&from=paste&height=677&id=u1d5e8ead&margin=%5Bobject%20Object%5D&name=image.png&originHeight=1354&originWidth=1042&originalType=binary&ratio=1&size=765947&status=done&style=none&taskId=u3febd66f-57f5-4855-b3d3-9fe48cc9ee6&width=521)
<a name="FyghC"></a>
# 事务操作 spring事务管理介绍

- 事务添加到 三层架构中的service层 (业务逻辑层)
- 在spring中进行事务管理操作
   - 编程式事务管理
   - 声明式事务管理  ( 常用
- 声明式事务管理
   - 基于注解方式使用(常用
   - 基于xml配置方式
- 在spring进行声明式事务管理,底层使用的aop原理
- spring事务管理api
   - 提供一个接口,代表事务管理器,这个接口针对不同的框架做了不同的实现,换言之,不管使用哪种数据源,都可以通过不同的实现来做到事务管理

![image.png](https://cdn.nlark.com/yuque/0/2021/png/1608527/1631846332100-8113b591-7b8a-45f7-a6c8-f346feb022d6.png#clientId=u4d21e6cd-1ca8-4&from=paste&height=361&id=u1f4de813&margin=%5Bobject%20Object%5D&name=image.png&originHeight=722&originWidth=1552&originalType=binary&ratio=1&size=1390229&status=done&style=none&taskId=u978ec2fa-37cd-4fc5-b34d-1ddbcaeebf0&width=776)
<a name="pMoD5"></a>
# 事务操作( 注解声明式事务管理

- spring配置文件配置事务管理器
```java
<?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 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">

    <!-- 组件扫描 -->
    <context:component-scan base-package="com.addicated"></context:component-scan>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:8889/zentao" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

    <!-- JdbcTemplate对象注册 -->
    <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>

service类上 ,或者service类方法上面添加事务注解

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional(readOnly = false,timeout = -1,propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
public class UserService {

    //注入dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney() {
//        try {
            //第一步 开启事务

            //第二步 进行业务操作
            //lucy少100
            userDao.reduceMoney();

            //模拟异常
            int i = 10/0;

            //mary多100
            userDao.addMoney();

            //第三步 没有发生异常,提交事务
//        }catch(Exception e) {
            //第四步 出现异常,事务回滚
//        }
    }
}

image.png

参数说明

Propagation 事务传播行为

  • 多事务方法直接进行调用,这个过程中事务是如何进行管理的
  • 事务传播行为 事务方法: 对数据库表数据进行变化的操作

image.png

Isolation 事务隔离级别

  • 事务有特性叫做隔离型,多事务操作之间不会产生影响,不考虑隔离型会产生很多问题
  • 脏读,不可重复读,幻读
    • 脏读: 一个未提交事务读到了另一个未提交事务的数据
    • image.png
    • 不可重复读: 一个未提交事务读取到另一提交事务修改的数据
    • image.png
    • 幻读:一个为提交事务读取到另一提交事务添加的数据
  • 解决
    • 通过设置事务隔离级别来解决

image.png

timeout 超时时间

  • 事务需要子啊一定时间内进行提交,如果不提交就进行回滚
  • 默认值为-1,-1为不设定超市时间,单位为秒

    readonly 是否只读

  • 读,查询操作,写,添加修改删除操作

  • readonly 默认为false 表示可以查询,可以crud
  • 设置为true的话,表示只能查询

    rollback 回滚

  • 设置出现哪些异常进行事务回滚

    事务操作(xml声明式事务管理

  • 在spring配置文件中进行配置

    • 1 配置事务管理器
    • 2 配置通知

      <?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 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">
      
      <!-- 组件扫描 -->
      <context:component-scan base-package="com.atguigu"></context:component-scan>
      
      <!-- 数据库连接池 -->
      <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
           destroy-method="close">
         <property name="url" value="jdbc:mysql:///user_db" />
         <property name="username" value="root" />
         <property name="password" value="root" />
         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      </bean>
      
      <!-- JdbcTemplate对象 -->
      <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
         <!--注入dataSource-->
         <property name="dataSource" ref="dataSource"></property>
      </bean>
      
      <!--1 创建事务管理器-->
      <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>
      

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

      ```java package com.atguigu.spring5.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”) //组件扫描 @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; // } }

```