11.事务-尚硅谷Spring零基础入门到进阶,一套搞定spring6全套视频教程(源码级讲解)

JdbcTemplate

Spring框架对JDBC进行封装,使用JdbcTemplate方便实现对数据库操作

运行准备

  1. 创建子模块

  2. 添加依赖

    <!--spring jdbc spring持久化层支持jar包-->  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-jdbc</artifactId>  
        <version>6.0.2</version>  
    </dependency>  
    
    <!--MySQL驱动-->  
    <dependency>  
        <groupId>mysql</groupId>  
        <artifactId>mysql-connector-java</artifactId>  
        <version>8.0.30</version>  
    </dependency>  
    <!--数据源-->  
    <dependency>  
        <groupId>com.alibaba</groupId>  
        <artifactId>druid</artifactId>  
        <version>1.2.15</version>  
    </dependency>
    
  3. 创建jdbc.properties

    	jdbc.user=root  
    	jdbc.password=root  
    	jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false  
    	jdbc.driver=com.mysql.cj.jdbc.Driver
    
  4. 创建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: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:property-placeholder location="jdbc.properties"/>  
        <!--配置JdbcTemplate-->  
    
        <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">  
            <!--装配数据源-->  
            <property name="url" value="${jdbc.url}"></property>  
            <property name="driverClassName" value="${jdbc.driver}"></property>  
            <property name="username" value="${jdbc.user}"></property>  
            <property name="password" value="${jdbc.password}"></property>  
        </bean>    <!--创建JdbcTemplate对象,注入数据源-->  
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
            <property name="dataSource" ref="druidDataSource"></property>  
        </bean></beans>
    
  5. 创建数据库表

    CREATE DATABASE `spring`;
    use `spring`;
    CREATE TABLE `t_emp` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(20) DEFAULT NULL COMMENT '姓名',
    `age` int(11) DEFAULT NULL COMMENT '年龄',
    `sex` varchar(2) DEFAULT NULL COMMENT '性别',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    
  6. 创建表对应实体类

    package com.example.jdbc;  
    
    import lombok.Data;  
    import lombok.ToString;  
    
    @Data  
    @ToString  
    public class Emp {  
        private Integer id;  
        private String name;  
        private Integer age;  
        private String sex;  
    }
    

curd操作

package com.example.jdbc;  
  
import com.example.jdbc.Emp;  
import org.junit.jupiter.api.Test;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.jdbc.core.BeanPropertyRowMapper;  
import org.springframework.jdbc.core.JdbcTemplate;  
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;  
  
import java.util.List;  
  
@SpringJUnitConfig(locations = "classpath:bean.xml")  
public class JdbcTemplateJunit {  
    @Autowired  
    private JdbcTemplate jdbcTemplate;  
  
    @Test  
    public void updateTest1() {  
        //1.添加操作  
        //第一步编写sql语句  
        String sql = "INSERT INTO t_emp VALUES(NULL,?,?,?)";  
        //第二步调用jdbcTemplate的方法,传入相关参数  
        Object[] params = {"东方不败", 20, "未知"};  
        //返回值rows是查询影响的行数  
        int rows = jdbcTemplate.update(sql, params);  
        jdbcTemplate.update(sql, "岳不群", 40, "未知");  
        jdbcTemplate.update(sql, "林平之", 20, "未知");  
    }  
  
    @Test  
    public void updateTest2() {  
        //2.修改操作  
        String sql = "UPDATE t_emp SET name=? WHERE id=?";  
        jdbcTemplate.update(sql, "林平之atguigu", 3);  
    }  
  
    @Test  
    public void updateTest3() {  
        //3,删除操作  
        String sql = "DELETE FROM t_emp WHERE id=?";  
        jdbcTemplate.update(sql, 1);  
    }  
  
    @Test  
    public void updateTest4() {  
        //3,查询操作  
        //写法一,手动封装  
        String sql = "SELECT * FROM t_emp WHERE id=?";  
        Emp empResult = jdbcTemplate.queryForObject(sql,  
                (rs, rowNum) -> {  
                    Emp emp = new Emp();  
                    emp.setId(rs.getInt("id"));  
                    emp.setName(rs.getString("name"));  
                    emp.setAge(rs.getInt("age"));  
                    emp.setSex(rs.getString("sex"));  
                    return emp;  
                }, 2);  
        System.out.println(empResult);  
        //写法二  
        Emp empResult2 = jdbcTemplate.queryForObject(sql,  
                new BeanPropertyRowMapper<>(Emp.class), 2);  
        System.out.println(empResult2);  
    }  
  
    @Test  
    public void updateTest5() {  
        //3,查询集合操作  
        String sql = "SELECT * FROM t_emp";  
        List<Emp> query = jdbcTemplate.query(sql,  
                new BeanPropertyRowMapper<>(Emp.class));  
        System.out.println(query);  
    }  
  
    @Test  
    public void updateTest6() {  
        //3,返回单个值  
        String sql = "SELECT Count(*) FROM t_emp";  
        Integer query = jdbcTemplate.queryForObject(sql,  
                Integer.class);  
        System.out.println(query);  
    }  
}

事务

事务基本概念

①什么是事务
数据库事务(transaction)是访问并可能操作各种数据项的一个数据库操作序列,这些操作要么全部执行,要么全部
不执行,是一个不可分割的工作单位。事务由事务开始与事务结束之间执行的全部数据库操作组成。
②事务的特性ACID
A:原子性(Atomicity)
一个事务(transaction)中的所有操作,要么全部完成,要么全部不完成,不会结束在中间某个环节。事务在执行过
程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。
C:一致性(Consistency)
事务的一致性指的是在一个事务执行之前和执行之后数据库都必须处于一致性状态。
如果事务成功地完成,那么系统中所有变化将正确地应用,系统处于有效状态。
如果在事务中出现错误,那么系统中的所有变化将自动地回滚,系统返回到原始状态。
l:隔离性(Isolation)
指的是在并发环境中,当不同的事务同时操纵相同的数据时,每个事务都有各自的完整数据空间。由并发事务所做
的修改必须与任何其他并发事务所做的修改隔离。事务查看数据更新时,数据所处的状态要么是另一事务修改它之
前的状态,要么是另一事务修改它之后的状态,事务不会查看到中间状态的数据。
D:持久性(Durability)
指的是只要事务成功结束,它对数据库所做的更新就必须保存下来。即使发生系统崩溃,重新启动数据库系统后,
数据库还能恢复到事务成功结束时的状态。

编程式事务

事务功能的相关操作全部通过自己编写代码来实现:

try{
	//开启事务,关闭事务的自动提交
	conn.setAutoCommit(false);
	//核心操作

	//提交事务
	conn.commit();
	}catch(Exception e){
	//回滚事务
	//conn.rollBack();
}finally{
	conn.close();
}

编程式事务缺陷:

  • 细节没有被屏蔽:具体操作过程中,所有细节都需要程序员自己来完成,比较繁琐。
  • 代码复用性不高:如果没有有效抽取出来,每次实现功能都需要自己编写代码,代码就没有得到复用。

声明式事务

使用框架将固定模式的代码抽取出来,进行相关的封装。封装起来后,只需要在配置文件中进行简单的配置即可完成操作。

  • 好处1:提高开发效率
  • 好处2:消除了冗余的代码
  • 好处3:框架会综合考虑相关领域中在实际开发环境下有可能遇到的各种问题,进行了健壮性、性能等各个方面的优化

创建案例

案例分析:用户具有余额属性,书本具有库存和价格属性,当用户购买书时用户余额减少书的价格书的库存减少1

  1. 创建表

    CREATE TABLE `t_book`(  
    	 `book_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',  
    	 `book_name` varchar(20) DEFAULT NULL COMMENT '图书名称',  
    	 `price` int(11) DEFAULT NULL COMMENT '价格',  
    	 `stock` int(10) unsigned DEFAULT NULL COMMENT '库存(无符号)',  
    	 PRIMARY KEY (`book_id`)  
    )ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;  
    insert into`t_book` (`book_id`,`book_name`,`price`,`stock`) values (1,'斗破苍穹',80,100),(2,'斗罗大陆',50,100);  
    CREATE TABLE `t_user`(  
    	 `User_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',  
    	 `username`varchar(20) DEFAULT NULL COMMENT '用户名',  
    	 `balance`int(10) unsigned DEFAULT NULL COMMENT '余额(无符号)',  
    	 PRIMARY KEY (`user_id`)  
    )ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;  
    insert into `t_user` (`user_id`,`username`,`balance`) values (1,'admin',500);
    
  2. 创建Book和User的MVC架构

    1. Dao接口

      package com.example.tx.dao;  
      
      public interface BookDao {  
          Integer getPriceById(Integer bookId);  
      
          Integer getStockById(Integer bookId);  
      
          int UpdateStock(int stock, Integer bookId);  
      }
      
      package com.example.tx.dao;  
      
      public interface UserDao {  
          Integer getBalanceByUserId(Integer userId);  
      
          int UpdateUserBalance(Integer balance, Integer userId);  
      }
      
    2. Dao实现类

      package com.example.tx.dao;  
      
      
      import org.springframework.beans.factory.annotation.Autowired;  
      import org.springframework.jdbc.core.JdbcTemplate;  
      import org.springframework.stereotype.Repository;  
      
      @Repository  
      public class BookDaoImpl implements BookDao {  
          @Autowired  
          private JdbcTemplate jdbcTemplate;  
      
          @Override  
          public Integer getPriceById(Integer bookId) {  
              String sql = "select price from t_book where book_id=?";  
              Integer price = jdbcTemplate.queryForObject(sql, Integer.class, bookId);  
              return price;  
          }  
      
          @Override  
          public Integer getStockById(Integer bookId) {  
              String sql = "select stock from t_book where book_id=?";  
              Integer stock = jdbcTemplate.queryForObject(sql, Integer.class, bookId);  
              return stock;  
          }  
      
          @Override  
          public int UpdateStock(int stock, Integer bookId) {  
              String sql = "update t_book set stock=? where book_id=?";  
              int rows = jdbcTemplate.update(sql, stock, bookId);  
              return rows;  
          }  
      }
      
      package com.example.tx.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  
          JdbcTemplate jdbcTemplate;  
      
          @Override  
          public Integer getBalanceByUserId(Integer userId) {  
              String sql = "select balance from t_user where user_id=?";  
              Integer balance = jdbcTemplate.queryForObject(sql, Integer.class, userId);  
              return balance;  
          }  
      
          @Override  
          public int UpdateUserBalance(Integer balance, Integer userId) {  
              String sql = "update t_user set balance=? where user_id=?";  
              int rows = jdbcTemplate.update(sql, balance, userId);  
              return 0;  
          }  
      }
      
    3. Service接口

      package com.example.tx.service;  
      
      public interface BookService {  
          Boolean BuyBook(Integer bookId, Integer userId);  
      }
      
      package com.example.tx.service;  
      
      public interface UserService {  
      }
      
    4. Service实现类

      package com.example.tx.service;  
      
      import com.example.tx.dao.BookDao;  
      import com.example.tx.dao.UserDao;  
      import org.springframework.beans.factory.annotation.Autowired;  
      import org.springframework.stereotype.Service;  
      
      @Service  
      public class BookServiceImpl implements BookService {  
          @Autowired  
          BookDao bookDao;  
          @Autowired  
          UserDao userDao;  
      
          @Override  
          public Boolean BuyBook(Integer bookId, Integer userId) {  
              //根据图书ID查询图书的价格和存量  
              //查价格  
              Integer price = bookDao.getPriceById(bookId);  
              //查存量  
              Integer stock = bookDao.getStockById(bookId);  
              //查询用户余额是否能够买书  
              //查询用户余额  
              Integer balance = userDao.getBalanceByUserId(userId);  
              //获得余额和书本价格的差价  
              Integer newBalance = balance - price;  
              if (newBalance >= 0) {  
                  //可以购买  
                  //能买,用户余额-图书价格,图书库存-1  
                  bookDao.UpdateStock(stock - 1, bookId);  
                  userDao.UpdateUserBalance(newBalance, userId);  
                  return true;        } else {  
                  //不能购买  
                  return false;  
              }  
          }  
      }
      
      package com.example.tx.service;  
      
      import com.example.tx.dao.UserDao;  
      import org.springframework.beans.factory.annotation.Autowired;  
      import org.springframework.stereotype.Service;  
      
      @Service  
      public class UserServiceImpl implements UserService {  
          @Autowired  
          UserDao userDao;  
      }
      
    5. Controller

      package com.example.tx.controller;  
      
      import com.example.tx.service.BookService;  
      import org.springframework.beans.factory.annotation.Autowired;  
      import org.springframework.stereotype.Controller;  
      
      @Controller  
      public class BookController {  
          @Autowired  
          BookService bookService;  
      
          public Boolean buyBook(Integer BookId, Integer UserId) {  
              bookService.BuyBook(BookId, UserId);  
              return false;    }  
      }
      
      package com.example.tx.controller; 
      import com.example.tx.service.UserService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Controller;
      
      @Controller
      public class UserController {
      @Autowired
      UserService userService;
      } 
      
    6. 输出结果

      无控制台输出结果,数据库中User的balance将减少50,Book的stock将减少1
      {: id="20240215105534-yglw4vb" updated="20240215105534"}
      

案例添加事务

  1. 修改买书的方法,删除判断用户余额是否足够买书的判断

    public Boolean BuyBook(Integer bookId, Integer userId) {  
    		        //根据图书ID查询图书的价格和存量  
    		        //查价格  
    		        Integer price = bookDao.getPriceById(bookId);  
    		        //查存量  
    		        Integer stock = bookDao.getStockById(bookId);  
    		        //查询用户余额是否能够买书  
    		        //查询用户余额  
    		        Integer balance = userDao.getBalanceByUserId(userId);  
    		        //获得余额和书本价格的差价  
    		        Integer newBalance = balance - price;  
    		        //if (newBalance >= 0) {  
    		            //可以购买  
    		            //能买,用户余额-图书价格,图书库存-1  
    		        bookDao.UpdateStock(stock - 1, bookId);  
    		        userDao.UpdateUserBalance(newBalance, userId);  
    		            //return true;        } else {  
    		            //不能购买  
    		            //return false;
    		            return true;  
    		        }  
    		    }  
    
  2. 修改数据库中用户的余额,使用户的余额不足以买书。这个操作等价于以下操作

    //传入一个负数
    bookDao.UpdateStock(stock - 1, bookId);  
    userDao.UpdateUserBalance(-100, userId);  
    
  3. 再次运行程序,会得到一个报错

    Caused by: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Out of range value for column 'balance' at row 1
    

    原因是用户余额字段不允许是负数。此时购买失败,但书的库存减少了

  4. 开启开启事务功能

    <?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: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/beans/spring-tx.xsd  
    ">  
        <!--开启扫描-->  
        <context:component-scan base-package="com.example"/>  
        <!--引入外部数据源-->  
        <context:property-placeholder location="jdbc.properties"/>  
        <!--配置JdbcTemplate-->  
    
        <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">  
            <!--装配数据源-->  
            <property name="url" value="${jdbc.url}"></property>  
            <property name="driverClassName" value="${jdbc.driver}"></property>  
            <property name="username" value="${jdbc.user}"></property>  
            <property name="password" value="${jdbc.password}"></property>  
        </bean>    <!--创建JdbcTemplate对象,注入数据源-->  
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
            <property name="dataSource" ref="druidDataSource"></property>  
        </bean>    <!--通过注解@Transactional,所标识的方法或标识的类中所有的方法,都会被事务管理器管理    -->  
        <!--事务注解需要添加约束  
        xmlns:tx="http://www.springframework.org/schema/tx"            http://www.springframework.org/schema/tx    http://www.springframework.org/schema/beans/spring-tx.xsd  -->    <tx:annotation-driven />  
    </beans>
    
  5. 给buyBook方法添加@Transactional注解

  6. 再次运行程序,程序报错,但数据库中书本的库存数据没有减少

事务相关策略

  1. readonly=true只读:设置只读,只能查询,不能修改添加删除

  2. timeout=-1超时:在设置超时时候之内没有完成,抛出异常回滚。时间单位为秒,设为-1表示永不超时

  3. 回滚策略:设置引发哪些异常时不进行回滚。声明式事务默认只针对运行时异常回滚,编译时异常不回滚。

    • rollbackFor:需要设置一个Class类型的对象
    • rollbackForClassName:需要设置一个字符串类型的全类名
    • noRollbackFor:需要设置一个Class类型的对象
    • rollbackFor:需要设置一个字符串类型的全类名
  4. 隔离级别:读问题

    @Transactional(isolation=Isolation.DEFAULT)//使用数据库默认的隔离级别
    @Transactional(isolation=Isolation.READ_UNCOMMITTED)//读未提交
    @Transactional(isolation=Iso1 ation.READ_COMMITTED)//读已提交
    @Transactional(isolation=Isolation.REPEATABLE_READ)//可重复读
    @Transactional(isolation=Iso1 ation.SERIALIZABLE)//串行化
    

    各个隔离级别解决并发问题的能力见下表:

    隔离级别脏读不可重复读幻读
    READ_UNCOMMITTED
    READ_COMMITTED
    REPEATABLE_READ
    SERIALIZABLE

    各种数据库产品对事务隔离级别的支持程度:

    隔离级别oraclemysql
    READ_UNCOMMITTED
    READ_COMMITTED有(默认)
    REPEATABLE_READ有(默认)
    SERIALIZABLE
  5. 传播行为:事务方法之间调用,事务如何使用

    什么是事务的传播行为?

    在service类中有a()方法和b()方法,a()方法上有事务,b()方法上也有事务,当a()方法执行过程中调用了b()方法,事务是如何传递的?合并到一个事务里?还是开启一个新的事务?这就是事务传播行为。
    一共有七种传播行为:

    • REQUIRED:支持当前事务,如果不存在就新建一个(默认)【没有就新建,有就加入】
    • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行【有就加入,没有就不管了】
    • MANDATORY:必须运行在一个事务中,如果当前没有事务正在发生,将抛出一个异常【有就加入,没有就
      抛异常】
    • REQUIRES_NEW:开启一个新的事务,如果一个事务已经存在,则将这个存在的事务挂起【不管有没有,直
      接开启一个新事务,开启的新事务和之前的事务不存在嵌套关系,之前事务被挂起】
    • NOT_SUPPORTED:以非事务方式运行,如果有事务存在,挂起当前事务【不支持事务,存在就挂起】
    • NEVER:以非事务方式运行,如果有事务存在,抛出异常【不支持事务,存在就抛异常】
    • NESTED:如果当前正有一个事务在进行中,则该方法应当运行在一个嵌套式事务中。被嵌套的事务可以独立于外层事务进行提交或回滚。如果外层事务不存在,行为就像REQUIRED一样。【有事务的话,就在这个事务里再嵌套一个完全独立的事务,嵌套的事务可以独立的提交和回滚。没有事务就和REQUIRED一样。】
    1. 修改数据库中表的数值

      user_idusernamebalance
      1admin101
      book_idbook_namepricestock
      1斗破苍穹100100
      2斗罗大陆200200
      令用户购买两本书,但余额中只能够购买第一本书
    2. 为buyBook添加事务属性

      package com.example.tx.service;  
      
      import com.example.tx.dao.BookDao;  
      import com.example.tx.dao.UserDao;  
      import org.springframework.beans.factory.annotation.Autowired;  
      import org.springframework.stereotype.Service;  
      import org.springframework.transaction.annotation.Propagation;  
      import org.springframework.transaction.annotation.Transactional;  
      
      @Service  
      public class BookServiceImpl implements BookService {  
          @Autowired  
          BookDao bookDao;  
          @Autowired  
          UserDao userDao;  
      
          @Transactional(propagation = Propagation.REQUIRED)  
          @Override  
          public Boolean BuyBook(Integer bookId, Integer userId) {  
              //根据图书ID查询图书的价格和存量  
              //查价格  
              Integer price = bookDao.getPriceById(bookId);  
              //查存量  
              Integer stock = bookDao.getStockById(bookId);  
              //查询用户余额是否能够买书  
              //查询用户余额  
              Integer balance = userDao.getBalanceByUserId(userId);  
              //获得余额和书本价格的差价  
              Integer newBalance = balance - price;  
      //        if (newBalance >= 0) {  
              //可以购买  
              //能买,用户余额-图书价格,图书库存-1  
              bookDao.UpdateStock(stock - 1, bookId);  
              userDao.UpdateUserBalance(newBalance, userId);  
      //            userDao.UpdateUserBalance(-100, userId);  
              return true;  
      //        } else {  
              //不能购买  
      //            return false;  
          }  
      }
      
    3. 创建CheckoutService接口和实现类,让用户批量买书
      CheckoutService

      package com.example.tx.service;  
      
      public interface CheckoutService {  
          void checkOut(Integer[] bookIds,Integer userId);  
      }
      

      CheckoutServiceImpl

      package com.example.tx.service;  
      
      import org.springframework.beans.factory.annotation.Autowired;  
      import org.springframework.stereotype.Service;  
      import org.springframework.transaction.annotation.Transactional;  
      
      @Service  
      public class CheckoutServiceImpl implements CheckoutService{  
          @Autowired  
          BookService bookService;  
          @Transactional  
          //一个用户批量买多本书  
          @Override  
          public void checkOut(Integer[] bookIds, Integer userId) {  
              for(int i = 0;i < bookIds.length; i++){  
                  bookService.BuyBook(bookIds[i],userId);  
              }  
          }  
      }
      
    4. 在BookController中调用checkOut方法
      UserController

      package com.example.tx.controller;  
      
      import com.example.tx.service.BookService;  
      import com.example.tx.service.CheckoutService;  
      import org.springframework.beans.factory.annotation.Autowired;  
      import org.springframework.stereotype.Controller;  
      
      @Controller  
      public class BookController {  
          @Autowired  
          BookService bookService;  
          @Autowired  
          CheckoutService checkoutService;  
      
          public Boolean buyBook(Integer bookId, Integer userId) {  
              bookService.BuyBook(bookId, userId);  
              return false;    }  
          public void checkout(Integer[] bookIds, Integer userId){  
              checkoutService.checkOut(bookIds,userId);  
          }  
      }
      
    5. 编写测试方法

      @Test  
      public void testCheckout() {  
          Integer bookIds[] = {1,2};  
          Integer userId = 1;  
          bookController.checkout(bookIds, userId);  
      }
      
    6. 输出结果
      无控制台输出,启动程序后抛出数据库报错,查看数据库书的库存没有减少

基于注解的声明式事务开发

  1. 创建一个config

    package com.example.tx.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("com.example.tx")  
    @EnableTransactionManagement  
    public class config {  
    
        @Bean  
        public DruidDataSource getDruidDataSource(){  
            DruidDataSource druidDataSource=new DruidDataSource();  
            //jdbc.user=root  
            //jdbc.password=root        //jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false        //jdbc.driver=com.mysql.cj.jdbc.Driver  
            druidDataSource.setUsername("root");  
            druidDataSource.setPassword("root");  
            druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false");  
            druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");  
            return druidDataSource;  
        }  
        @Bean(name = "jdbcTemplate")  
        public JdbcTemplate getJdbcTemplate(DataSource dataSource){  
            JdbcTemplate jdbcTemplate=new JdbcTemplate();  
            jdbcTemplate.setDataSource(dataSource);  
            return jdbcTemplate;  
        }  
        //事务管理器  
        @Bean  
        public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){  
            DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();  
            dataSourceTransactionManager.setDataSource(dataSource);  
            return dataSourceTransactionManager;  
        }  
    }
    
  2. bean.xml配置全部注释掉

  3. 编写新的测试类

    import com.example.tx.config.config;  
    import com.example.tx.controller.BookController;  
    import org.junit.jupiter.api.Test;  
    import org.springframework.context.ApplicationContext;  
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
    
    public class test {  
        @Test  
        public void testAnno(){  
            ApplicationContext applicationContext=new AnnotationConfigApplicationContext(config.class);  
            BookController bookController=applicationContext.getBean(BookController.class);  
            Integer bookIds[] = {1,2};  
            Integer userId = 1;  
            bookController.checkout(bookIds, userId);  
        }  
    }
    
  4. 运行结果:

    无控制台输出,启动程序后抛出数据库报错,查看数据库书的库存没有减少

基于xml

  1. 创建bean-xml.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: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/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  
    ">  
        <!--开启扫描-->  
        <context:component-scan base-package="com.example"/>  
        <!--引入外部数据源-->  
        <context:property-placeholder location="jdbc.properties"/>  
        <!--配置JdbcTemplate-->  
        <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">  
            <!--装配数据源-->  
            <property name="url" value="${jdbc.url}"/>  
            <property name="driverClassName" value="${jdbc.driver}"/>  
            <property name="username" value="${jdbc.user}"/>  
            <property name="password" value="${jdbc.password}"/>  
        </bean>    <!--创建JdbcTemplate对象,注入数据源-->  
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
            <property name="dataSource" ref="druidDataSource"/>  
        </bean>    <!--通过注解@Transactional,所标识的方法或标识的类中所有的方法,都会被事务管理器管理    -->  
        <!--事务管理器-->  
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
            <property name="dataSource" ref="druidDataSource"/>  
        </bean>    <!--配置事务增强    -->  
        <tx:advice id="advice" transaction-manager="transactionManager">  
            <tx:attributes>  
                <!--设置所有get开头的方法只读            -->  
                <tx:method name="get*" read-only="true"/>  
                <!--设置所有update开头的方法传播行为为REQUIRED            -->  
                <tx:method name="update*" propagation="REQUIRED"/>  
            </tx:attributes>  
        </tx:advice>  
        <!--配置切入点和通知使用的方法        -->  
        <aop:config>  
            <!-- 此处配置了"execution(* com.example.*.*(..))导致事务不回滚"       -->  
            <aop:pointcut id="pt" expression="execution(* com.example.tx.*(..))"/>  
            <aop:advisor advice-ref="advice" pointcut-ref="pt"/>  
        </aop:config>  
    </beans>
    
  2. 添加aop依赖

    <dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-aspects</artifactId>  
    <version>4.3.7.RELEASE</version>  
    </dependency>  
    
    <dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-aop</artifactId>  
    <version>4.3.7.RELEASE</version>  
    </dependency>
    
  3. 编写测试类

    package com.example.tx.test;  
    
    import com.example.tx.controller.BookController;  
    import org.junit.jupiter.api.Test;  
    import org.springframework.beans.factory.annotation.Autowired;  
    import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;  
    
    @SpringJUnitConfig(locations = "classpath:bean-xml.xml")  
    public class XMLTest {  
        @Autowired  
        BookController bookController;  
    
        @Test  
        public void testCheckout() {  
            Integer bookIds[] = {1, 2};  
            Integer userId = 1;  
            bookController.checkout(bookIds, userId);  
        }  
    
        @Test  
        public void testJunit() {  
            System.out.println("1");  
        }  
    }
    
  4. 运行结果:

    无控制台输出,启动程序后抛出数据库报错,查看数据库书的库存没有减少

  • 22
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值