40-49、Spring5之事务操作

117 阅读4分钟

事务概念

1、什么是事务

  1. 事务时数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败
  2. 典型场景:银行转账(甲转账100元给乙,甲少100元,乙多100元)

2、事务四大特性

  1. 原子性
  2. 一致性
  3. 隔离性
  4. 持久性

搭建事务操作环境

image.png

1、 创建数据库表,添加记录

image.png

2、 创建service,搭建dao,完成对象创建和注入关系

  1. service注入dao,在dao注入JdbcTemplate,在JdbcTemplate注入DataSource

3、 在dao创建两个方法:多钱和少钱的方法,在service创建方法(转账的方法)

UserService代码

package com.atguigu.spring5.service;

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

@Service
public class UserService {
    // 注入dap
    @Autowired
    private UserDao userDao;

    // 转账的操作
    public void accountsMoney() {
        // lucy少100
        userDao.addMoney();
        // mary多100
        userDao.reduceMoney();
    }
}

UserDao代码

package com.atguigu.spring5.dao;

public interface UserDao {
    // 多钱
    public void addMoney();
    // 少钱
    public void reduceMoney();
}

UserDaoImpl代码

package com.atguigu.spring5.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;

    // lucy转账100给mary
    // 多钱
    @Override
    public void addMoney() {
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }
    // 少钱
    @Override
    public void reduceMoney() {
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }
}

测试代码

package com.atguigu.spring5.test;

import com.atguigu.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testAffair {
    @Test
    public void test1() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountsMoney();
    }
}

4、 上面代码,如果正常执行没有问题的,但是如果代码执行过程中出现异常,有问题

image.png

  • 上面问题如何解决呢?
    使用事务进行解决
  • 事务操作过程

image.png

Spring事务管理介绍

1、事务添加到JavaEE三层结构里面Service层(业务逻辑层)

2、在Spring进行事务管理操作

  1. 有两种方式:编程式事务管理和声明式事务管理(使用)

3、声明式管理

  1. 基于注解方式
  2. 基于xml配置文件方式

4、在Spring进行声明式事务管理,底层使用AOP原理

5、Spring事务管理API

  1. 提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类

image.png

注解声明式事务管理

  1. 在Spring配置文件配置事务管理器
<!--  创建事务管理器  -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--   注入数据源     -->
    <property name="dataSource" ref="dataSource"></property>
</bean>
  1. 在Spring配置文件,开启事务注解

    1. 在spring配置文件引入名称空间tx
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:util="http://www.springframework.org/schema/util"
           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/util http://www.springframework.org/schema/util/spring-util.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">
    
    1. 开启事务注解
    <!--  开启事务注解  -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    
  2. 在service类上面(获取service类里面方法上面)添加事务注解

    1. @Transactional,这个注解添加到类上面,也可以添加方法上面
    2. 如果把这个注解添加类上面,这个类里面所有的方法都添加事务
    3. 如果把这个注解添加类里面的方法上面,为这个方法添加事务
    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.Transactional;
    
    @Service
    @Transactional
    public class UserService {
        // 注入dap
        @Autowired
        private UserDao userDao;
    
        // 转账的操作
        public void accountsMoney() {
            // 第一步:开始事务
            // 第二步:进行业务操作
            // lucy少100
            userDao.addMoney();
            // 模拟异常
            int i = 10 / 0;
            // mary多100
            userDao.reduceMoney();
            // 第三步: 没有发生异常,提交事务
        }
    }
    

声明式事务管理参数配置

image.png

propagation:事务传播行为

当一个事务方法呗另外一个事务方法调用时候,这个事务方法如何进行 image.png image.png

@Transactional(propagation = Propagation.REQUIRED)

ioslation:事务隔离级别

  1. 事务由特性成为隔离性,多事务操作之前不会产生影响。不考虑隔离性产生很多问题
  2. 有三个读问题:脏读、不颗重复读、虚(幻)读
  3. 脏读:一个未提交事务读取到另一个未提交的数据 image.png
  4. 不可重复读:一个未提交事务读取到另一提交事务修改数据 image.png
  5. 虚读:一个未提交事务读取到另一提交事务添加数据
  6. 通过设置事务隔离级别,解决读问题

image.png

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

timeout:超时时间

  1. 事务需要在一定时间内进行提交,如果不提交进行回滚
  2. 默认值是-1,即不超时,设置时间以秒单位进行计算

readOnly:是否只读

  1. 读:查询操作,写:添加修改删除操作
  2. readOnly默认值false,即表示即可以查询,也可以添加修改删除操作
  3. 设置readOnly值是true,设置程true之后,只能查询

rollbackFor:回滚

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

noRollbackFor:不回滚

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

XML声明式事务管理

1、在spring配置文件中进行配置

  • 第一步:配置事务管理器
  • 第二步:配置通知
  • 第三步:配置切入点和切面
<?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:util="http://www.springframework.org/schema/util"
       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/util http://www.springframework.org/schema/util/spring-util.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 https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--  组件扫描  -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>
    <!--  引入外部配置连接池  -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClassName}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.username}"></property>
        <property name="password" value="${prop.password}"></property>
    </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>

    <!--  2 配置通知  -->
    <tx:advice id="txadvice">
        <!--    配置事务参数    -->
        <tx:attributes>
            <!--     指定那种规则的方法上面添加事务       -->
            <tx:method name="accountsMoney" propagation="REQUIRED"/>
<!--            <tx:method name="accounts*"/>-->
        </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:advisor>
    </aop:config>
</beans>

完全注解开发

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

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.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/book?rewriteBatchedStatements=true");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        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 dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}

测试代码

@Test
public void test3() {
    ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
    UserService userService = context.getBean("userService", UserService.class);
    userService.accountsMoney();
}