关于Spring事务管理的基础实例

1.准备工作(环境:idea)

    我是用dbcp连接池连接的,所以必须的jar包除了Spring的基础包外还得有aspectweaver,mysqlconnector,commons-dbcp2,commons-pool2的包。

2.框架结构

 

 A)Dao层

  BookShopDao

package com.laola.dao;

public interface BookShopDao {
//通过编号查询书的价格
public int findBookPriceByIsbn(String Isbn); //通过编号查询书的库存 public void updateBookStock(String Isbn); //通过名字查余额 public void updateBalance(String username,int price); }

Cashier

package com.laola.dao;

import java.util.List;

public interface Cashier {
    void checkout(String username, List<String> isbns);
}

实现类

BookServiceImpl

package com.laola.Impl;

import com.laola.dao.BookShopDao;
import com.laola.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

//@Transactional (这里定义一个事务。注:如果不想配置XML文件可以用这些注解)
//@Service
public class BookServiceImpl implements BookService {
    //@Autowired
    private BookShopDao bookShopDao;

    public void setBookShopDao(BookShopDao bookShopDao) {
        this.bookShopDao = bookShopDao;
    }

    @Override
    public void purchase(String username, String Isbn) {
//获取价格
int price=bookShopDao.findBookPriceByIsbn(Isbn);
//更新库存 bookShopDao.updateBookStock(Isbn);
//更新余额 bookShopDao.updateBalance(username,price); } }

BookShopDaoImpl

package com.laola.Impl;

import com.laola.dao.BookShopDao;
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;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    //实现价格查询
    @Override
    public int findBookPriceByIsbn(String isbn) {

        String sql="select price from book where Isbn = ?";

        return jdbcTemplate.queryForObject(sql,Integer.class,isbn);
    }
    //实现库存更新
    @Override
    public void updateBookStock(String isbn) {
        String sql2="select stock from stock where Isbn = ?";
        Integer stock = jdbcTemplate.queryForObject(sql2, Integer.class, isbn);
        if(stock<0){
//当库存不足时,抛出异常并回滚
throw new RuntimeException("库存不足!"); } String sql="update stock set stock=stock-1 where Isbn=?"; jdbcTemplate.update(sql,isbn); } //实现余额更新 @Override public void updateBalance(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 RuntimeException("余额不足!"); } String sql="update account set balance=balance-? where username=?"; jdbcTemplate.update(sql,price,username); } }
CashierImpl
package com.laola.Impl;

import com.laola.dao.Cashier;
import com.laola.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
//事务的传播
//@Transactional //@Service public class CashierImpl implements Cashier { //@Autowired private BookService bookService; public void setBookService(BookService bookService) { this.bookService = bookService; } @Override public void checkout(String username, List<String> isbns) {
//遍历购买的书,事务的传播
for(String isbn:isbns){ bookService.purchase(username,isbn); } } }

Service层

BookService

package com.laola.service;

public interface BookService {

    void purchase(String username,String Isbn);
}

XML配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       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/context  http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <context:component-scan base-package="com.laola" />
    <context:property-placeholder location="db.properties"/>
<!--定义连接池的bean--> <bean name ="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="username" value="${user}" /> <property name="password" value="${password}"/> <property name="url" value="${url}"/> <property name="driverClassName" value="${driver}"/> </bean>
<!--定义jdbc模板--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
<!--定义事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="bookShopDao" class="com.laola.Impl.BookShopDaoImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> <bean id="bookService" class="com.laola.Impl.BookServiceImpl"> <property name="bookShopDao" ref="bookShopDao"/> </bean> <bean id="cashier" class="com.laola.Impl.CashierImpl"> <property name="bookService" ref="bookService"/> </bean> <!-- 配置事务属性--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 配置事务切点--> <aop:config> <aop:pointcut id="txpointcut" expression="execution(* com.laola.service.BookService.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txpointcut"/> </aop:config> </beans>

Test类

package com.laola.test;

import com.laola.dao.BookShopDao;
import com.laola.dao.Cashier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;

public class BookShopTest {
    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
        BookShopDao bookShopDao=(BookShopDao) ac.getBean(BookShopDao.class);
        //int price = bookShopDao.findBookPriceByIsbn("1");
        Cashier bean = ac.getBean(Cashier.class);
//将用户购买的书放在集合,然后封装到请求参数中 bean.checkout(
"tom", Arrays.asList("1","2")); //System.out.println(price); } }

 

posted @ 2019-04-22 16:59  人迹罕至的那条路  阅读(274)  评论(0编辑  收藏  举报