zoukankan      html  css  js  c++  java
  • srping 事物管理

    1. 准备工作

      1> 添加接口 BookShopDao

    package com.tx;
    
    public interface BookShopDao {
        
        //根据书号获取书的单价
        public int findBookPriceByIsbn(int isbn);
        
        //更新书的库存, 使书号对应的书的库存 -1
        public void updateBookStock(int isbn);
        
        //更新用户账户余额: 使 username 的 balance - price
        public void updateUserAccount(String username, int price);
    }
    View Code

      2> 添加接口 BookShopDao 的实现类 BookShopDaoImpl

    package com.tx;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    import org.springframework.stereotype.Repository;
    
    @Repository("bookShopDao")
    public class BookShopDaoImpl implements BookShopDao{
        
        @Autowired
        private JdbcTemplate jdbcTemplate;
        
        @Override
        public int findBookPriceByIsbn(int isbn) {
            String sql = "select price from book where isbn = ?";
            
            return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
        }
    
        @Override
        public void updateBookStock(int isbn) {
            String sql2 = "select stock from book_stock where isbn = ?";
            Integer num = jdbcTemplate.queryForObject(sql2, Integer.class, isbn);
            if(num == 0) {
                throw new BookStockException("库存不足");
            }
            
            String sql = "update book_stock set stock = stock-1 where isbn = ?";
            jdbcTemplate.update(sql, isbn);
        }
    
        @Override
        public void updateUserAccount(String username, int price) {
            String sql2 = "select balance from account where username = ?";
            Integer balance = jdbcTemplate.queryForObject(sql2, Integer.class, username);
            if(balance < price) {
                throw new BookAccountException("余额不足");
            }
            
            String sql = "update account set balance = balance-? where username = ?";
            jdbcTemplate.update(sql, price, username);
        }
    
    }
    View Code

      3> 添加 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:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jdbc="http://www.springframework.org/schema/jdbc"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
            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-4.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
                
                <context:component-scan base-package="com.tx"></context:component-scan>
                <context:property-placeholder location="classpath:db.properties"/>
                <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                    <property name="user" value="${jdbc.user}"></property>
                    <property name="password" value="${jdbc.password}"></property>
                    <property name="driverClass" value="${jdbc.driverClass}"></property>
                    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
                    <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
                    <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
                </bean>
                
                <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                    <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"/>
    </beans>
    View Code

      4> 添加测试类 SpringTest

    package com.tx;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SpringTest {
        
        private ApplicationContext ctx;
        private BookShopDao bookShopDao;
        private BookShopService bookShopService;
        
        {
            ctx = new ClassPathXmlApplicationContext("bean-jdbc.xml");
            bookShopDao = ctx.getBean(BookShopDaoImpl.class);
            bookShopService = ctx.getBean(BookShopService.class);
        }
        
        /**
         * 测试 根据书号获取书的单价
         */
        @Test
        public void testFind() {
            int price = bookShopDao.findBookPriceByIsbn(1002);
            System.out.println(price);
        }
        
        /**
         * 测试 更新书的库存, 使书号对应的书的库存 -1
         */
        @Test
        public void testUpdateStock() {
            bookShopDao.updateBookStock(1001);
        }
        
        /**
         * 测试 更新用户账户余额: 使 username 的 balance - price
         */
        @Test
        public void testUpdateAccount() {
            bookShopDao.updateUserAccount("AA", 20);
        }
        
        /**
         * 测试  事物
         */
        @Test
        public void testPurchase() {
            bookShopService.purchase("AA", 1001);
        }
    
    }
    View Code

      5> 添加 BookShopService 接口

    package com.tx;
    
    public interface BookShopService {
        public void purchase(String username, int isbn);
    }
    View Code

      6> 添加 BookShopServiceImpl 实现类

    package com.tx;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    public class BookShopServiceImpl implements BookShopService {
        
        @Autowired
        private BookShopDao bookShopDao;
        
        @Transactional  //添加事物注解
        @Override
        public void purchase(String username, int isbn) {
            //1. 获取书的单价
            int price = bookShopDao.findBookPriceByIsbn(isbn);
            
            //2. 更新库存
            bookShopDao.updateBookStock(isbn);
            
            //3. 更新账户余额
            bookShopDao.updateUserAccount(username, price);
        }
    
    }
    View Code

      7> 添加 BookAccountException 和 BookStockException 异常类

    package com.tx;
    
    public class BookAccountException extends RuntimeException{
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        public BookAccountException() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        public BookAccountException(String message, Throwable cause, boolean enableSuppression,
                boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
            // TODO Auto-generated constructor stub
        }
    
        public BookAccountException(String message, Throwable cause) {
            super(message, cause);
            // TODO Auto-generated constructor stub
        }
    
        public BookAccountException(String message) {
            super(message);
            // TODO Auto-generated constructor stub
        }
    
        public BookAccountException(Throwable cause) {
            super(cause);
            // TODO Auto-generated constructor stub
        }
        
    }
    View Code
    package com.tx;
    
    public class BookStockException extends RuntimeException{
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        public BookStockException() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        public BookStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
            // TODO Auto-generated constructor stub
        }
    
        public BookStockException(String message, Throwable cause) {
            super(message, cause);
            // TODO Auto-generated constructor stub
        }
    
        public BookStockException(String message) {
            super(message);
            // TODO Auto-generated constructor stub
        }
    
        public BookStockException(Throwable cause) {
            super(cause);
            // TODO Auto-generated constructor stub
        }
    }
    View Code

    2. 配置事物管理器

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    3. 启用事物注解

    <tx:annotation-driven transaction-manager="transactionManager"/>

    4. 添加事物注解  (在需要进行事物处理的地方加入事物注解)

    @Transactional  //添加事物注解
    @Override
    public void purchase(String username, int isbn) {

     5. 事物注解详解

    /**
    * 添加事物注解
    * 1. 使用 propagation 指定事物的传播行为,(由内而外传播) 即当前的事物方法被另外一个事物方法调用时
    * 如何使用事物, 默认取值为 REQUIRED, 即使用调用方法的事物(也就是说, 买2本书, 要么全部成功购买, 要么事物回滚)
    * REQUIRES_NEW : 表示新开启一个事物,调用的事物方法的事物被挂起 (意思是, 如果够买一本的钱,就买一本, 其他回滚)
    *
    * 2. 使用 isolation 指定事物的隔离级别, 最常用的取值为 READ_COMMITTED(读已提交)
    *
    * 3. 默认情况下 Spring 的声明式事物对所有的运行时异常进行回滚, 也可以通过对应的属性进行设置
    * noRollbackFor: 对指定异常不进行回滚 , 也就不是一个事物了, 也可由其他回滚设置, 通常情况取默认值
    *
    * 4. 使用 readOnly 指定事物是否只读, 不更新数据, 若真的是一个只读取数据库的方法, 应设置为 : readOnly = true
    *
    * 5. 使用 timeout 指定强制回滚之前事物可以占用的时间, 也就是在指定时间还没执行完成就回直接进行回滚,单位为秒
    */
    @Transactional(propagation=Propagation.REQUIRES_NEW, isolation=Isolation.READ_COMMITTED,
            noRollbackFor= {BalanceException.class}, readOnly = false, timeout=1)
    @Override
    public void buyBook(String username, int isbn) {

  • 相关阅读:
    Linux 下 MQ 的安装
    云计算的三种服务模式:IaaS,PaaS和SaaS
    Mac下安装Maven
    JDK Mac 安装
    Mac OS 终端利器 iTerm2
    单元测试用例规范
    boolean 属性的定义规范
    2019-12-9号 终于入职 阿里巴巴
    远程调试方法
    系统提测及上线规范(系统上线必读!)
  • 原文地址:https://www.cnblogs.com/redhat0019/p/8884830.html
Copyright © 2011-2022 走看看