zoukankan      html  css  js  c++  java
  • Spring入门第二十六课

    Spring中的事务管理

    事务简介

    事务管理是企业级应用程序开发中必不可少的技术,用来确保数据的完整性和一致性。

    事务就是一系列的动作,他们被当做一个单独的工作单元,这些动作要么全部完成,要么全部不起作用。

    事务的四个关键属性(ACID)

    -原子性(atomicity):事务是一个原子操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用。

    -一致性(consistency):一旦所有事务动作完成,事务就被提交,数据和资源就处于一种满足业务规则的一致性状态中。

    -隔离性(isolation):可能有许多事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏

    -持久性(durability):一旦事务完成,无论发生什么系统错误,它的结果都不应该受到影响,通常情况下,事务的结果被写到持久化存储器中。

    作为企业级应用程序框架,Spring在不同的事务管理API纸上定义了一个抽象层,而应用程序开发人员不必了解底层的事务管理API,就可以使用Spring的事务管理机制。

    Spring即支持编程式事务管理,也支持声明式事务管理。

    编程式事务管理:将事务管理代码嵌入到业务方法中来控制事务的提交和回滚,在编程式管理事务时,必须在每个事务操作中包含而外的事务管理代码。

    声明式事务管理:大多数情况下,比编程式事务管理更好用,它将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。事务管理作为一种横切关注点,可以通过AOP方法模块化,Spring通过Spring AOP框架支持生命是事务管理。

    Spring从不同的事务管理API中抽象了一整套的事务机制,开发人员不必了解底层食物API,就可以利用这些事务机制。有了这些事务机制,事务管理代码就能独立于特定的事务技术了。

    Spring的核心事务管理抽象是org.springframework.transaction.interface.Plateform.TransactionManager管理封装了一组独立于技术的方法,无论使用Spring的哪种书屋管理策略(编程式或声明式),事务管理器都是必须的。

    先看事务准备

    看代码:

    db.properties

    jdbc.user=root
    jdbc.password=logan123
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring
    
    jdbc.initPoolSize=5
    jdbc.maxPoolSize=10

    applicationContext.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"
        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-4.3.xsd">
    
        <context:component-scan base-package="logan.study.spring.tx"></context:component-scan>
    
        <!-- 导入资源文件 -->
        <context:property-placeholder location="classpath:db.properties"/>
    
        <!-- 配置C3P0数据源 -->
        <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="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
            <property name="driverClass" value="${jdbc.driverClass}"></property>
            
            <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
            <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
        </bean>
        
        <!-- 配置Spring的JDBCTemplate -->
        <bean id="jdbcTemplate"
        class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        
        <!-- 配置NamedParameterJdbcTemplate,该对象可以使用具名参数,其没有无参的构造器,所以必须为其构造器指定参数 -->
        <bean id="namedParameterJdbcTemplate"
        class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
            <constructor-arg ref="dataSource"></constructor-arg>
        </bean>
    </beans>
    package logan.study.spring.tx;
    
    public interface BookShopDao {
        //根据书号获取书的单价
        public int findBookPriceIsbn(String isbn);
        
        //更新书的库存,使书号对应的库存-1
        public void updateBookStock(String isbn);
        
        
        public void updateUserAccount(String username,int price);
    
    }
    package logan.study.spring.tx;
    
    public class BookStockException extends RuntimeException{
    
        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
        }
        
        
    
    }
    package logan.study.spring.tx;
    
    public class UserAccountException extends RuntimeException{
    
        public UserAccountException() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        public UserAccountException(String message, Throwable cause, boolean enableSuppression,
                boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
            // TODO Auto-generated constructor stub
        }
    
        public UserAccountException(String message, Throwable cause) {
            super(message, cause);
            // TODO Auto-generated constructor stub
        }
    
        public UserAccountException(String message) {
            super(message);
            // TODO Auto-generated constructor stub
        }
    
        public UserAccountException(Throwable cause) {
            super(cause);
            // TODO Auto-generated constructor stub
        }
        
        
    
    }
    package logan.study.spring.tx;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    
    @Repository("bookShopDao")
    public class BookShopDaoImpl implements BookShopDao {
        
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        @Override
        public int findBookPriceIsbn(String isbn) {
            // TODO Auto-generated method stub
            String sql = "SELECT price FROM book WHERE isbn=?";
            return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
        }
    
        @Override
        public void updateBookStock(String isbn) {
            // TODO Auto-generated method stub
            //检查书的库存是否足够,若不够,则抛出异常
            String sql2 = "SELECT stock FROM book_stock WHERE isbn = ?";
            int stock = jdbcTemplate.queryForObject(sql2, Integer.class, isbn);
            if(stock == 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) {
            // TODO Auto-generated method stub
            //检查书的库存是否足够,若不够,则抛出异常
            String sql2 = "SELECT balance FROM account WHERE username = ?";
            int balance = jdbcTemplate.queryForObject(sql2, Integer.class, username);
            if(balance < price){
                throw new UserAccountException("余额不足!");
            }
            String sql = "UPDATE account SET balance = balance - ? WHERE username = ?";
            jdbcTemplate.update(sql, price, username);
    
        }
    
    }
    package logan.study.spring.tx;
    
    public interface BookShopService {
        
        public void purchase(String username, String isbn);
    
    }
    package logan.study.spring.tx;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service("bookShopService")
    public class BookShopServiceImpl implements BookShopService {
        
        @Autowired
        private BookShopDao bookShopDao;
    
        @Override
        public void purchase(String username, String isbn) {
            // TODO Auto-generated method stub
            //1.获取书的单价
            int price = bookShopDao.findBookPriceIsbn(isbn);
            //2.更新书的库存
            bookShopDao.updateBookStock(isbn);
            //3.更新用户余额
            bookShopDao.updateUserAccount(username, price);
            
    
        }
    
    }
    package logan.study.spring.tx;
    
    import static org.junit.Assert.*;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    public class SpringTransactionTest {
        
        private ApplicationContext ctx = null;
        private BookShopDao bookShopDao = null;
        private BookShopService bookShopService = null;
        {
            ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            bookShopDao = ctx.getBean(BookShopDao.class);
            bookShopService = ctx.getBean(BookShopService.class);
        }
        
        @Test
        public void testBookShopService(){
            bookShopService.purchase("AA", "1001");
        }
        
        
        @Test
        public void testBookShopDaoUpdateUserAcount(){
            bookShopDao.updateUserAccount("AA", 100);
        }
        
        @Test
        public void testBookShopDaoUpdateBookStock(){
            bookShopDao.updateBookStock("1001");
        }
        
        @Test
        public void testBookShopDaoFindPriceByIsbn(){
            System.out.println(bookShopDao.findBookPriceIsbn("1001"));
        }
    
        @Test
        public void test() {
            fail("Not yet implemented");
        }
    
    }

    可以看到在service里面买书时,不是事务的,所以如果用户的余额不足时,书的库存减少了,但是用户的余额没减少,抛出异常。

  • 相关阅读:
    Azureus 3.0.0.8
    KchmViewer 3.0
    GNOME 2.18.0 正式版颁发宣布
    Emacs 22.0.95
    gTwitter:Twitter 的 Linux 客户端
    KDE DVD Authoring Wizard-易用的 DVD 制造器材
    GIMP 2.3.15
    Monit-零碎看监工具
    Cobras-专注于 Qt 的 IDE
    K3b 1.0 正式版公布
  • 原文地址:https://www.cnblogs.com/LoganChen/p/6915279.html
Copyright © 2011-2022 走看看