Spring5框架基础详解(六)(事务概念和四大特性、搭建事务操作环境、事务操作过程演示、事务操作(Spring事务管理介绍)、注解声明式事务管理、声明式事务管

152 阅读5分钟

本人已参与[新人创作礼]活动,一起开启掘金创作之路。


一、事务概念

事务是数据库操作最基本单元,指的是逻辑上的一组操作。要么都成功,如果一个失败所有操作都失败。
事务的四大特性(ACID):
				*1.原子性:
						  操作这些指令时,要么全部执行成功,要么全部不执行。
						  只要其中一个指令执行失败,所有的指令都执行失败,数据进行回滚,回到执行指令前的数据状态。
				       	  eg:拿转账来说,假设用户A和用户B两者的钱加起来一共是20000,那么不管AB之间如何转账,转几次账,事务结束后两个用户的钱相加起来应该还得是20000,这就是事务的一致性。
				*2.一致性:
						 事务的执行使数据从一个状态转换为另一个状态,但是对于整个数据的完整性保持稳定。
				*3.隔离性:
						 隔离性是当多个用户并发访问数据库时,比如操作同一张表时,数据库为每一个用户开启的事务,不能被其他事务的操作所干扰,多个并发事务之间要相互隔离。
				*4.持久性:
						 当事务正确完成后,它对于数据的改变是永久性的。

二、搭建事务操作环境

在这里插入图片描述

1.创建数据库,创建表

在这里插入图片描述

2.创建service,搭建dao,完成对象创建和注入关系
		*1.在service注入dao,在dao里注入JdbcTemplate,在JdbcTemplate注入DataSource
package cn.hncj.dao;

public interface UserDao {

}



package cn.hncj.dao;

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

/**
 * Created on 2022/3/22.
 *
 * @author Hou chaof
 */
@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;

}



package cn.hncj.Service;

import cn.hncj.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created on 2022/3/22.
 *
 * @author Hou chaof
 */
@Service
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;

}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property><!--驱动名称-->
        <property name="url" value="jdbc:mysql:///db"></property><!--数据库地址-->
        <property name="username" value="root"></property><!--连接数据库用户名-->
        <property name="password" value=""></property><!--连接数据库用户密码-->
    </bean>
    <!--JDBCTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--开启组件扫描-->
    <context:component-scan base-package="cn.hncj"></context:component-scan>
</beans>
3.在dao创建两个方法,多钱和少钱的方法,在service创建方法(转账的方法)

package cn.hncj.dao;

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



package cn.hncj.dao;

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

/**
 * Created on 2022/3/22.
 *
 * @author Hou chaof
 */
@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");
    }

}





package cn.hncj.Service;

import cn.hncj.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created on 2022/3/22.
 *
 * @author Hou chaof
 */
@Service
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;

    //转账方法
    public void accountMoney(){
        //lucy少100
        userDao.reduceMoney();
        //mary多100
        userDao.addMoney();
    }
}





import cn.hncj.Service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created on 2022/3/22.
 *
 * @author Hou chaof
 */
public class TestBook {
    @Test
    public void testAccount(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();
    }
}

在这里插入图片描述

三、事务操作过程(这种编程式事务管理不常用,但要了解)

在这里插入图片描述

四、事务操作(Spring事务管理介绍)

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

五、事务操作(注解声明式事务管理)

步骤1.在spring配置文件配置事务管理器
<!--创建一个事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
步骤2.在spring配置文件,开启事务注解
			*1.在spring配置文件引入名称空间tx
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
步骤2.在spring配置文件,开启事务注解
			*2.开启事务注解
  <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
步骤3.在service类上面(或者service类里面方法上面)添加事务注解@Transactional
		*注解在类上面,表示这个类的所有方法都可以添加事务
		*注解在方法上面,仅为方法添加事务 

六、声明式事务管理参数配置

1.在service类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数。
		*参数1:propagation:事务传播行为
				*多事务方法之间进行调用,这个过程中事务是如何进行管理的。
@Transactional(propagation = Propagation.REQUIRED)

在这里插入图片描述

		*参数2:ioslation:事务隔离级别(为解决三个读的问题)
					*事务的隔离性,在多事务之间不会产生影响,不考虑隔离性产生很多问题。
					*有三个读的问题:脏读、不可重复读、幻读
							*脏读:一个未提交事务读取到另一个未提交事务的数据
							*不可重复读:一个未提交的事务读取到另一个提交事务修改的数据
							*幻读:一个未提交事务读取到另一提交事务添加数据
					*通过设置事务隔离级别,解决读问题。		(MySQL默认隔离级别:可重复读)
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)

在这里插入图片描述

		*参数3:timeout:超时时间
				*事务需要在一定时间内进行提交,如果不提交进行回滚。
				*默认值(默认时间):-1,设置时间以秒为单位
@Transactional(timeout = -1,propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
		*参数4readOnly:是否只读
				*读:查询操作; 写:添加修改删除操作
				*默认值是false,表示可以查询,可以添加修改删除操作
				*设置readOnly值是true,只能查询
@Transactional(readOnly=true,timeout = -1,propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
		*参数5:rollbackFor:回滚
				*设置出现哪些异常进行事务回滚
		*参数6:noRollbackFor:不回滚
				*设置出现哪些异常不进行事务回滚