• Spring框架——事务管理方式搭建一个小的项目


    学习Spring框架,通过事务管理的方式搭建一个小的项目,该项目可以查询对数据库中的图书库存数量进行修改。


    首先,使用MVC分层的设计模式思想搭建项目目录结构。
    这里写图片描述

    此部分代码源码之中都有相关注释,所以尽情附上源码。

    首先Dao层的源码:

    package com.jredu.book.Dao;
    
    public interface BookDao {
    
        /**
         * 通过编号查询书的价格
         * @param isbn
         * @return
         */
        int findBookPriceByIsbn(String isbn);
    
        /**
         * 通过用户名查询余额
         * @param username
         * @return
         */
        int findBalanceByUsername(String username);
    
        /**
         * 更新书的库存
         * @param isbn
         */
        void updateBookStock(String isbn,int stock);
    
        /**
         * 通过编号查询库存数量
         * @param isbn
         * @return
         */
        int findStockByIsbn(String isbn);
    
    
        /**
         * 更新用户余额信息
         * @param username
         * @param price
         */
        void updateAccountBalance(String username,int price);
    }
    

    dao.impl相关的源码:

    package com.jredu.book.Dao.Impl;
    
    import java.util.Map;
    
    import javax.sql.DataSource;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.support.JdbcDaoSupport;
    import org.springframework.stereotype.Repository;
    import org.springframework.stereotype.Service;
    
    import com.jredu.book.Dao.BookDao;
    import com.jredu.book.entity.Account;
    import com.jredu.book.entity.Book;
    
    @Repository
    public class BookDaoImpl extends JdbcDaoSupport implements BookDao{
    
    
        @Autowired
        public void setDS(DataSource dataSource){
            setDataSource(dataSource);
        }
    
        @Override
        public int findStockByIsbn(String isbn) {
            // TODO Auto-generated method stub
            String sql = "select * from book_stock where isbn=?";
            Map<String, Object> bookStock= getJdbcTemplate().queryForMap(sql,isbn);
            int stock = Integer.parseInt(bookStock.get("stock").toString());
            return stock;
        }
    
        @Override
        public int findBookPriceByIsbn(String isbn) {
            // TODO Auto-generated method stub
            String sql="select * from book where isbn=?";
            Book book = getJdbcTemplate().queryForObject(sql, new Book(), isbn);
            return book.getPrice();
        }
    
        @Override
        public int findBalanceByUsername(String username) {
            // TODO Auto-generated method stub
            String sql = "select * from account where username=?";
            Account account = getJdbcTemplate().queryForObject(sql, new Account(),username);
            return account.getBalance();
        }
    
        @Override
        public void updateBookStock(String isbn,int stock) {
            // TODO Auto-generated method stub
            String sql="update book_stock set stock=? where isbn=?";
            getJdbcTemplate().update(sql,stock,isbn);
    
        }
    
        @Override
        public void updateAccountBalance(String username, int price) {
            // TODO Auto-generated method stub
            String sql="update account set balance=? where username=?";
            getJdbcTemplate().update(sql,price,username);
        }
    
    }
    

    entity实体类的相关源码:

    package com.jredu.book.entity;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import org.springframework.jdbc.core.RowMapper;
    
    public class Account implements RowMapper<Account>{
    
        private String username;
        private int balance;
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public int getBalance() {
            return balance;
        }
        public void setBalance(int balance) {
            this.balance = balance;
        }
        @Override
        public Account mapRow(ResultSet rs, int arg1) throws SQLException {
            // TODO Auto-generated method stub
            Account account = new Account();
            account.setUsername(rs.getString("username"));
            account.setBalance(rs.getInt("balance"));
            return account;
        }
    
    
    }
    
    package com.jredu.book.entity;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import org.springframework.jdbc.core.RowMapper;
    
    public class Book implements RowMapper<Book>{
    
        private String isbn;
        private String bookName;
        private int price;
        public String getIsbn() {
            return isbn;
        }
        public void setIsbn(String isbn) {
            this.isbn = isbn;
        }
        public String getBookName() {
            return bookName;
        }
        public void setBookName(String bookName) {
            this.bookName = bookName;
        }
        public int getPrice() {
            return price;
        }
        public void setPrice(int price) {
            this.price = price;
        }
        @Override
        public Book mapRow(ResultSet rs, int arg1) throws SQLException {
            // TODO Auto-generated method stub
            Book book = new Book();
            book.setIsbn(rs.getString("isbn"));
            book.setBookName(rs.getString("book_name"));
            book.setPrice(rs.getInt("price"));
            return book;
        }
    
    
    
    }
    

    service目录下的相关源码:

    package com.jredu.book.service;
    
    public interface BookService {
    
        void purchase(String isbn,String username);
    }
    
    package com.jredu.book.service;
    
    public interface MoneyService {
    
        void purchase(String isbn,String username);
    }
    

    service接口即service.impl目录下的相关源码:

    package com.jredu.book.service.Impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    
    import com.jredu.book.Dao.BookDao;
    import com.jredu.book.service.BookService;
    @Repository
    public class BookServiceImpl implements BookService{
    
        @Autowired
        private BookDao dao;
    
        @Override
        public void purchase(String isbn, String username) {
            // TODO Auto-generated method stub
            int stock = dao.findStockByIsbn(isbn);
            //库存要大于1本
            if(stock>0){
                int price = dao.findBookPriceByIsbn(isbn);
                int balance = dao.findBalanceByUsername(username);
                //余额是否大于书的价格
                if(balance>=price){
                    //执行更新余额信息
                    dao.updateAccountBalance(username, balance-price);
                    //更新库存信息
                    dao.updateBookStock(isbn, stock-1);
                }
            }
        }
    
    }
    

    编写一个测试类,book.test目录下测试类源码:

    package com.jredu.book.test;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.jredu.book.service.BookService;
    import com.jredu.book.service.MoneyService;
    
    public class BookTest {
    
        public static void main(String[] args) {
            ApplicationContext app= new ClassPathXmlApplicationContext("applicationContext-book.xml");
            BookService service = app.getBean(BookService.class);
            service.purchase("abc","wang");
            System.out.println("业务完成");
    
        }
    }
    

    最重要的部分是配置application-book.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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:util="http://www.springframework.org/schema/util"
        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/util
            http://www.springframework.org/schema/util/spring-util.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!-- 自动扫描 -->
        <context:component-scan base-package="com.jredu.book"></context:component-scan>    
        <!-- 配置C3P0数据源 -->
        <!-- 导入资源文件 -->
        <context:property-placeholder location="classpath:jdbc.properties"/>
        <bean
            id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
            p:user="${jdbc.user}"
            p:password="${jdbc.pwd}"
            p:driverClass="${jdbc.driverClassName}"
            p:jdbcUrl="${jdbc.url}"
            p:initialPoolSize="${jdbc.initPoolSize}"
            p:maxPoolSize="${jdbc.maxPoolSize}"
        />
        <!-- 配置事务管理器 -->
        <bean
        id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref="dataSource"
        />
        <!-- 事务的通知 -->
        <tx:advice
            id="booktxAdvice" transaction-manager="transactionManager"  
            >
            <tx:attributes>
                <tx:method name="purchase*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
    
        <aop:config>
            <aop:pointcut expression="execution (* com.jredu.book.service.*.*(..))" id="pointcut"/>
            <aop:advisor advice-ref="booktxAdvice" pointcut-ref="pointcut"/>
        </aop:config>
    
        <!-- 配置JDBC Template -->
        <bean
            id="jdbcTemplate"
            class="org.springframework.jdbc.core.JdbcTemplate"
            p:dataSource-ref="dataSource"
        />
    
    
    </beans>

    至此,使用事务方式搭建的一个小项目就已经完成,操作完成后,数据库中的图书库存数量会有所变化。

  • 相关阅读:
    数字签名与HTTPS详解
    利用策略模式优化过多 if else 代码
    Redis 的事务到底是不是原子性的
    Spring Boot项目的接口防刷
    深入分析 ThreadLocal
    什么是四层和七层负载均衡?他们之间的区别是什么?
    MyEclipse或Eclipse中project的导入和导出
    org.hibernate.exception.ConstraintViolationException: could not insert:
    C++ STL vector(向量容器)的使用(附完整程序代码)
    Swift2.0语言教程之函数嵌套调用形式
  • 原文地址:https://www.cnblogs.com/aixing/p/13327660.html
Copyright © 2020-2023  润新知