• 事务操作(详细讲解)


    一、事务概念

    1、什么是事务

    (1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败

    (2)典型场景:银行转账

    lucy转账100元给mary

    lucy少100 ,mary多100

    2、事务四个特性(ACID)

    (1)原子性

    (2)一致性

    (3)隔离性

    (4)持久性

    二、搭建事务操作环境

    在这里插入图片描述.

    1、加入依赖,并创建spring配置文件(bean.xml)
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>5.3.22version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>8.0.28version>
    dependency>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.13.2version>
        <scope>testscope>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.3.22version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-coreartifactId>
        <version>5.3.22version>
    dependency>
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.2.8version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    
    <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"
           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
    ">
    
        
        <context:component-scan base-package="com.jin">context:component-scan>
    
        
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            
            <property name="dataSource" ref="dataSource">property>
        bean>
    
        
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
            <property name="url" value="jdbc:mysql://localhost:3306/user_db?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        bean>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    2、创建数据库表,并创建实体类
    CREATE TABLE `t_account` (
    `id`  varchar(20) NOT NULL ,
    `username`  varchar(50) NULL ,
    `money`  int(255) NULL ,
    PRIMARY KEY (`id`)
    )
    
    INSERT INTO `t_account` (`id`, `username`, `money`) VALUES 
    ('1', 'lucy', '1000')
    ('2', 'mary', '1000')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在这里插入图片描述.

    public class User {
         private String id;
        private String username;
        private int money;
    
        //Getter和Setter方法
        //toString方法
        ...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    3、编写service和dao

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

    //Dao接口
    public interface UserDao {
        //多钱
        public void addMoney();
        //少钱
        public void reduceMoney();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    //业务逻辑层
    @Service
    public class UserService implements UserDao {
        @Autowired
        private UserDao userDao;
    
        @Override
        public void addMoney() {
    
            userDao.addMoney();
        }
    
        @Override
        public void reduceMoney() {
            userDao.reduceMoney();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    (2)在Dao接口实现类中调用JdbcTemplate对象里面的方法实现添加操作

    //Dao接口实现类
    @Repository
    @Primary   //@Primary 告诉spring 在犹豫的时候优先选择哪一个具体的实现。
    public class UserDaoImpl implements UserDao{
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        //少钱的方法
        //lucy转账100给mary
        @Override
        public void addMoney() {
            String sql = "update user_db.t_account set money=money-? where username=?";
            int i = jdbcTemplate.update(sql, 100, "lucy");
            System.out.println(i);
    
        }
    
        //多钱的方法
        //mary得到lucy转账的100
        @Override
        public void reduceMoney() {
            String sql = "update user_db.t_account set money=money+? where username=?";
            jdbcTemplate.update(sql,100,"mary");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    3、测试类
    public class test {
        @Test
        public void MyTest(){
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
            UserService userService = context.getBean("userService", UserService.class);
            userService.addMoney();
            userService.reduceMoney();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    4、上面的代码,如果正常执行则没有问题;但是如果代码执行过程中出现异常,则有问题!

    在这里插入图片描述.

    在这里插入图片描述.

    (1)上面的问题如何解决?

    答:使用事务进行解决

    (2)事务操作过程

    • 第一步:开启事务
    • 第二步:进行业务操作
    • 第三步:若没有发生异常,提交事务
    • 第四步:若出现异常,事务回滚

    三、事务管理介绍

    1、事务添加到JavaEE三层结构里面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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    2、在spring配置文件中,开启事务注解

    (1)在spring配置文件引入名称空间 tx

    
    <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: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/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd
    ">
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    (2)开启注解事务

     
        
        <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true">tx:annotation-driven>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    3、在service类上面(获取service类里面方法上面)添加事务注解

    (1)@Transactional :这个注解添加到类上面,也可以添加到方法上面

    (2)如果把这个注解添加到类上面,这个类里面所有的方法都添加事务

    (3)如果把这个注解添加到方法上面,为这个方法添加事务常用

    @Service
    @Transactional
    public class UserService implements UserDao {
    }
    
    • 1
    • 2
    • 3
    • 4
    4、如果代码执行过程中出现异常,则事务回滚!

    在这里插入图片描述.

  • 相关阅读:
    分销小程序开发|分销小程序怎么设计动态分销?
    数字 IC 设计、FPGA 设计秋招笔试题目、答案、解析(6)2022 紫光展锐数字芯片提前批笔试
    redis缓存命中率
    学会通知 | “中国人工智能学会—华为MindSpore学术奖励基金”第三期发布通知
    【编译原理】编译器前端
    Java进阶篇--AQS(AbstractQueuedSynchronizer)
    LeetCode 1710. 卡车上的最大单元数
    仿游戏热血江湖游戏类22(物品方法)
    【JDK21】初体验
    tensorflow神经网络多维曲线拟合
  • 原文地址:https://blog.csdn.net/weixin_45737330/article/details/126691755