Spring的事务操作一站式学习【事务的概念、注解声明式事务管理、声明式事务管理参数配置、XML声明式事务管理、完全注解声明式事务管理】(超详细)

事务的概念

事务的概念(通俗理解):事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败。

典型场景:银行转账(这两件事必须都成功或都不成功)
lucy 转账 100 元 给 mary
lucy 少 100,mary 多 100

事务四个特性(ACID)
(1)原子性:这个过程不可分割。
(2)一致性:操作之前和操作之后的总量不变。
(3)隔离性:多事务操作时不会相互参生影响。
(4)持久性:事务提交后数据库数据会发生变化。

搭建事务操作的环境

在这里插入图片描述

创建数据库表,添加记录

在这里插入图片描述

代码演示

(1)创建 service,搭建 dao,完成对象创建和注入关系。
(2)service 注入 dao,在 dao 注入 JdbcTemplate,在 配置文件中在JdbcTemplate 中注入 DataSource。
(3)在 dao 创建两个方法:多钱和少钱的方法,在 service 创建方法(转账的方法)。

jdbc.properties:

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/user_db?characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.username=root
jdbc.password=18044229

bean1.xml:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

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

    <!--引入外部的属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}" ></property>
        <property name="username" value="${jdbc.username}" ></property>
        <property name ="password" value="${jdbc.password}" ></property>

    </bean>

    <!--创建jdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入DataSource-->
        <property name="dataSource" ref="dataSource"></property>

    </bean>

</beans>

UserDao 接口:

package com.Keafmd.spring5.dao;

/**
 * Keafmd
 *
 * @ClassName: UserDao
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-20 10:09
 */

public interface UserDao {
    
    

    //多钱
    public void addMoney();

    //少钱
    public void reduceMoney();
}

实现类UserDaoImpl :

package com.Keafmd.spring5.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.sql.rowset.JdbcRowSet;

/**
 * Keafmd
 *
 * @ClassName: UserDaoImpl
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-20 10:09
 */
@Repository
public class UserDaoImpl implements UserDao{
    
    

    @Autowired
    private JdbcTemplate jdbcTemplate;


    //少钱
    @Override
    public void reduceMoney() {
    
    
        String sql = "update t_account set money =money-? where username =?";
        jdbcTemplate.update(sql,100,"Lucy");
    }


    //多钱
    @Override
    public void addMoney() {
    
    
        String sql = "update t_account set money =money+? where username =?";
        jdbcTemplate.update(sql,100,"Mary");
    }


}

UserService 类:

package com.Keafmd.spring5.service;

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

/**
 * Keafmd
 *
 * @ClassName: UserService
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-20 10:08
 */
@Service
public class UserService {
    
    

    //注入dao
    @Autowired
    private UserDao userDao;

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

        //Mary多100
        userDao.addMoney();

    }

}

测试类:

package com.Keafmd.spring5.test;

import com.Keafmd.spring5.config.TxConfig;
import com.Keafmd.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Keafmd
 *
 * @ClassName: TestAccount
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-20 10:40
 */
public class TestAccount {
    
    

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

测试前的数据:
在这里插入图片描述
测试后的数据:
在这里插入图片描述

这样正常执行,没有问题,但是如果中途出错了呢?接着往下看。

事务场景引入

上面代码,如果正常执行没有问题的,但是如果代码执行过程中出现异常,就会有问题,假如在Lucy少100后代码发生了错误,那么会怎样?
我们手动添加个错误:

//转账的方法
    public void accountMoney(){
    
    

        // Lucy 少100
        userDao.reduceMoney();

        //手动添加异常
        int i =100/0;

        //Mary多100
        userDao.addMoney();

    }

这样数据的变化就会出现问题。
测试前的数据:
在这里插入图片描述
测试后的数据:
在这里插入图片描述

这样就发生了问题,Lucy少了100但是Mary却没有多。这就需要利用事务来解决,让其在发生错误的时候进行回滚。

事务管理介绍

1、事务添加到 JavaEE 三层结构里面 Service 层(业务逻辑层)
2、在 Spring 进行事务管理操作
有两种方式:
(1)编程式事务管理(不方便)
(2)声明式事务管理(使用)
3、声明式事务管理
(1)基于注解方式(简单方便)
(2)基于 xml 配置文件方式
4、在 Spring 进行声明式事务管理,底层使用 AOP 原理
5、Spring 事务管理 API
提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类:

Spring中使用的是DataSourceTransactionManager
在这里插入图片描述

注解声明式事务管理

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

bean1.xml:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

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

    <!--引入外部的属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}" ></property>
        <property name="username" value="${jdbc.username}" ></property>
        <property name ="password" value="${jdbc.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>


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

</beans>

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

UserService 类:

package com.Keafmd.spring5.service;

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

/**
 * Keafmd
 *
 * @ClassName: UserService
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-20 10:08
 */
@Service
@Transactional  // @Transactional,这个注解添加到类上面
public class UserService {
    
    

    //注入dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney(){
    
    

        // Lucy 少100
        userDao.reduceMoney();

        //手动添加异常,事务回滚
        int i =100/0;

        //Mary多100
        userDao.addMoney();

    }

}

现在我们添加事务后带着异常运行测试类:

测试前的数据:
在这里插入图片描述
测试后的数据:
在这里插入图片描述

很明显的看到测试后的数据没有变化,是因为发生了异常,进行了事务回滚,所以数据库中的数据都没有改变。

声明式事务管理参数配置

在 service 类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数:
在这里插入图片描述

propagation:事务传播行为

事务传播行为:多事务方法直接进行调用,这个过程中事务 是如何进行管理的。

在这里插入图片描述
我们在add方法加了事务,update没有加,当我们的add调用update的时候,事务会怎么处理,这个过程就叫做事务的传播行为。有事务的方法调用没事务的,还有就是都有事务并且调用这些情况发生的时候事务会怎么处理,这些过程就叫做事务的传播行为。
事务的传播行为可以由传播属性指定。Spring 定义了7种类传播行为。
在这里插入图片描述
结合我们的例子介绍两种最常见的:
在这里插入图片描述

默认的是REQUIRED:@Transactional(propagation = Propagation.REQUIRED)相当于:@Transactional

ioslation:事务隔离级别

(1)事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
(2)有三个读问题:脏读、不可重复读、虚(幻)读

脏读(致命问题):一个未提交事务读取到另一个未提交事务的数据
在这里插入图片描述

不可重复读(现象):一个未提交事务读取到另一提交事务修改数据
在这里插入图片描述

虚读(现象):一个未提交事务读取到另一提交事务添加数据
不可重复读的重点是修改了数据,同样的条件 , 你读取过的数据 , 再次读取出来发现值不一样了。
幻读的重点是新增或者删除了数据 , 第 1 次和第 2 次读出来的记录数不一样。

解决:通过设置事务隔离级别,解决读问题。
在这里插入图片描述

设置隔离级别方式:@Transactional(isolation = Isolation.REPEATABLE_READ),这种可重复读是mysql默认的设置方式。

timeout:超时时间

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

设置方式:@Transactional(timeout = 5)

readOnly:是否只读

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

设置方式:@Transactional(readOnly = true)

rollbackFor:回滚

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

设置方式:@Transactional(rollbackFor=Exception.class)

noRollbackFor:不回滚

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

设置方式:@Transactional(notRollbackFor=RunTimeException.class)

XML声明式事务管理(不常用)

在 spring 配置文件中进行配置:
第一步:配置事务管理器
第二步:配置通知
第三步:配置切入点和切面

bean2.xml:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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/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
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

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

    <!--引入外部的属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}" ></property>
        <property name="username" value="${jdbc.username}" ></property>
        <property name ="password" value="${jdbc.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="accountMoney" propagation="REQUIRED"/>
            <!--<tx:method name="account*"/>-->
        </tx:attributes>
    </tx:advice>
    <!--3 配置切入点和切面-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="pt" expression="execution(* com.Keafmd.spring5.service.UserService.*(..))"/>
        <!--配置切面-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
    </aop:config>

</beans>

把UserService的@Transactional注解注释掉,其它不变,新建个测试类:

package com.Keafmd.spring5.test;

import com.Keafmd.spring5.config.TxConfig;
import com.Keafmd.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Keafmd
 *
 * @ClassName: TestAccount
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-20 10:40
 */
public class TestAccount {
    
    

    @Test
    public void test2(){
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        UserService userService = context.getBean("userService",UserService.class);
        userService.accountMoney();
    }

}

这样我们使用的是bean2.xml配置文件,那我们这就是XML声明式事务管理。

完全注解声明式事务管理

在注解声明式事务管理我们也是需要使用bean1.xml配置文件,我们也可以不使用配置文件,创建个配置类,和注解声明式事务管理相比其它类都不变。

TxConfig类:

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


/**
 * Keafmd
 *
 * @ClassName: TxConfig
 * @Description: 完全注解开发
 * @author: 牛哄哄的柯南
 * @date: 2021-01-20 21:16
 */
@Configuration //配置类
@ComponentScan(basePackages = "com.Keafmd")  //组件扫描
@EnableTransactionManagement  // 开启事务
public class TxConfig {
    
    

    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
    
    
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/user_db?characterEncoding=utf8&useUnicode=true&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("18044229");
        return dataSource;
    }

    //创建jdbcTemplate对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
    
    
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
    
    
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

}

测试类:

package com.Keafmd.spring5.test;

import com.Keafmd.spring5.config.TxConfig;
import com.Keafmd.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Keafmd
 *
 * @ClassName: TestAccount
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-20 10:40
 */
public class TestAccount {
    
    

	//使用配置类
    @Test
    public void test3(){
    
    
        ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
        UserService userService = context.getBean("userService",UserService.class);
        userService.accountMoney();
    }

}

这样我们就实现了完全注解声明式事务管理。

猜你喜欢

转载自blog.csdn.net/weixin_43883917/article/details/112911550