spring 事务总结

项目结构:

jar包文件

c3p0-0.9.1.2.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.3.jar
junit-4.9.jar
mysql-connector-java-5.1.7-bin.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar

 

1、配置 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"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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">

<!-- 配置Bean扫描 -->
<context:component-scan base-package="com.man.spring"></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>
<!-- 引入JdbcTemplate Bean -->
<bean id="jdbcTemplate"
    class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
    </bean>

<bean id="namedParameterJdbcTemplate"
    class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dataSource"></constructor-arg>
</bean>

<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 啟動事務註解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

db.properties

--db.properties
jdbc.user=root
jdbc.password=111111
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/spring4
jdbc.initPoolSize=5
jdbc.maxPoolSize=10

 

servie接口:

public interface BookShopService {
    public void purchase(String userName,String isbn);    

}

servie实现:

package com.man.spring.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookShopServiceImpl implements BookShopService {

    @Autowired
    private BookShopDao bookShopDao;
    
    //添加事務註解
    //1、使用Propagation 指定事务传播行为,即当前的事务方法被另外一个事务方法调用时
    //如何使用事务,默认取值为REQUIRED即使用调用方法的事务
    //REQUIRES_NEW:事务自动事务,调用的事务方法的事务被挂起
    //2、使用isolation:指定事务隔离级别,最常用的取值为READ_COMMITTED
    //3、默认情况下,Spring的声明式事务对所有的运行时异常进行回滚,也可以通过对应的属性进行设置,通常情况下去默认值即可
    //4、使用readOnly 指定事务是否为只读,表示这个事务只读取数据但不更新数据。这样可以帮助数据库引擎优化事务,若真的是一个只读取数据库值的方法,应设置readOnly=true
    //5、使用timeout 指定强制回滚之前的事务,可以占用的时间。
    //@Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED,noRollbackFor= {UserAccountException.class})
    @Transactional
    @Override
    public void purchase(String userName, String isbn) {
        
        int price=bookShopDao.findBookPriceByIsbn(isbn);
        
        bookShopDao.updateBookStock(isbn);
        
        bookShopDao.updateUserAccount(userName, price);    
    }
}

dao接口

package com.man.spring.tx;
public interface BookShopDao {
    /**
     * 根據
     * @param isbn
     * @return
     */
    public int findBookPriceByIsbn(String isbn);    
    /*
     * 
     */
    public void updateBookStock(String isbn);    
    public void updateUserAccount(String username,int price);
}

dao实现

package com.man.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 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 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) {
        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);
    }

}


UserAccountException.java

package com.man.spring.tx;
public class UserAccountException extends RuntimeException{
    /**
     * 
     */
    private static final long serialVersionUID = -1823508388585311709L;
    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 com.man.spring.tx;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestTx {
    
    private ApplicationContext ctx;
    private BookShopDao bookShopDao;    
    private BookShopService bookShopService;
        
    {
        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 testFindBookPriceByIsbn() {
        System.out.println(bookShopDao.findBookPriceByIsbn("1001"));
    }
    
    @Test
    public void testUpdateBookStock(){
        bookShopDao.updateBookStock("1001");
    }
    
    @Test
    public void testupdateUserAccount() {
        bookShopDao.updateUserAccount("AA", 1);
    }


}

 

posted @ 2019-05-26 21:51  珂瑞  阅读(99)  评论(0)    收藏  举报