注解实现的spring事务

接口

 1 package spring.transaction;
 2 
 3 public interface BookDao {
 4 
 5     //根据书名获取书的单价
 6     double findBookPriceByName(String bookName);
 7 
 8     //更新库存数
 9     void updateBookStock(String bookName);
10 
11     //更新买家账户金额
12     void updateBuyerAmount(String buyerName,double price);
13 
14     //更新卖家账户金额
15     void updateSellerAmount(String sellerName,double price);
16 
17 }
jdbcTemplate操作mysql
 1 package spring.transaction;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.jdbc.core.JdbcTemplate;
 5 import org.springframework.stereotype.Repository;
 6 
 7 
 8 @Repository(value = "BookDao")
 9 public class BookDaoImpl implements BookDao {
10 
11     @Autowired
12     private JdbcTemplate jdbcTemplate;
13 
14 
15     @Override
16     public double findBookPriceByName(String bookName) {
17         String sql = "SELECT `price` FROM `book` WHERE `name`=?";
18         return  jdbcTemplate.queryForObject(sql,double.class,bookName);
19     }
20 
21     @Override
22     public void updateBookStock(String bookName) {
23         String check = "SELECT `stock` FROM `book` WHERE `name`=?";
24         int result = jdbcTemplate.queryForObject(check,int.class,bookName);
25 
26         if (result>0){
27             String sql = "UPDATE `book` SET `stock`= `stock`-1  WHERE `name`=?";
28             jdbcTemplate.update(sql,bookName);
29         }else {
30             throw new RuntimeException("库存不足!");
31         }
32 
33 
34     }
35 
36     @Override
37     public void updateBuyerAmount(String buyerName, double price) {
38         String check = "SELECT `amount` FROM `buyer` WHERE `name`=?";
39         double result = jdbcTemplate.queryForObject(check,double.class,buyerName);
40         if(result>price){
41             String sql = "UPDATE `buyer` SET `amount`= `amount`-?  WHERE `name`=?";
42             jdbcTemplate.update(sql,price,buyerName);
43         }else {
44             throw new RuntimeException("余额不足!");
45         }
46 
47     }
48 
49     @Override
50     public void updateSellerAmount(String sellerName, double price) {
51         String sql = "UPDATE `seller` SET `amount`= `amount`+?  WHERE `name`=?";
52         jdbcTemplate.update(sql,price,sellerName);
53 
54     }
55 }

注解事务

 1 package spring.transaction;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Qualifier;
 5 import org.springframework.stereotype.Service;
 6 import org.springframework.transaction.annotation.Isolation;
 7 import org.springframework.transaction.annotation.Propagation;
 8 import org.springframework.transaction.annotation.Transactional;
 9 
10 @Service(value = "BookService")
11 public class BookService {
12 
13     @Autowired @Qualifier(value = "BookDao")
14     private BookDao dao;
15 
16     /**
17      * 买书的交易过程方法
18      * @param bookName  书名
19      * @param buyerName  买家名
20      * @param sellerName  卖家名
21      *
22      */
23 
24     /*
25      * 事务
26      *  - propagation 指定事务的传播行为
27      *      - 定义当前事务方法被另外一个事务方法调用是时,如何使用事务
28      *      - 默认是REQUIRED,也就是使用调用方法的事务
29      *      -REQUIRES_NEW 使用新事务
30      *
31      *  - isolation 指定事务的隔离级别
32      *      - 常用级别 READ_COMMITTED
33      *
34      *  - rollbackFor/noRollbackFor 定义要(不)执行回滚的异常
35      *
36      *  - readOnly 指定事务是否只读
37      *
38      *  - timeout 指定强制回滚之前事务可以占用的时间,单位是秒
39      */
40     @Transactional(propagation = Propagation.REQUIRES_NEW,
41                    isolation = Isolation.READ_COMMITTED,
42                    rollbackFor = Exception.class,
43                    readOnly = false,
44                    timeout = 3)
45     public void action(String buyerName,String sellerName,String bookName)  {//
46 
47 //            超时导致的事务强制回滚
48 //        try {
49 //            Thread.sleep(5000);
50 //        } catch (InterruptedException e) {
51 //            e.printStackTrace();
52 //        }
53         //获得单价
54         double price = dao.findBookPriceByName(bookName);
55 
56         //更新库存
57         dao.updateBookStock(bookName);
58 
59         //买家付款
60         dao.updateBuyerAmount(buyerName,price);
61 
62         //卖家收款
63         dao.updateSellerAmount(sellerName,price);
64     }
65 
66 
67 }

接口

1 package spring.transaction;
2 
6 public interface MulBookDao {
7      void mulAction( String buyerName, String sellerName,String... bookNameList);
8 }

实现类

 1 package spring.transaction;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Service;
 5 import org.springframework.transaction.annotation.Transactional;
 6 
 7 
 8 
 9 @Service("service")
10 public class MulBookDaoImpl implements MulBookDao {
11 
12     @Autowired
13     private BookService bookService;
14 
15 
16     //购买多本数
17     @Transactional
18     @Override
19     public void mulAction(String buyerName, String sellerName,String... bookNameList) {
20 
21         for (String bookName : bookNameList){
22             bookService.action(buyerName,sellerName,bookName);
23         }
24     }
25 }

测试类

 1 package spring.transaction;
 2 
 3 import org.junit.Before;
 4 import org.junit.Test;
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.support.ClassPathXmlApplicationContext;
 7 
 8 public class TransactionTest {
 9 
10     private ApplicationContext ac;
11     private MulBookDaoImpl service;
12 
13     @Before
14     public void init(){
15         ac = new ClassPathXmlApplicationContext("classpath:transaction.xml");
16         service = ac.getBean("service",MulBookDaoImpl.class);
17     }
18 
19 
20     @Test
21     public void test(){
22 
23         service.mulAction("Tom","LK","JAVA","C");
24     }
25 }

配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:p="http://www.springframework.org/schema/p"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:aop="http://www.springframework.org/schema/aop"
 7        xmlns:util="http://www.springframework.org/schema/util"
 8        xmlns:tx="http://www.springframework.org/schema/tx"
 9        xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 11 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 12 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd 13 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 14 15 16 <context:component-scan base-package="spring.transaction"/> 17 18 <!--自动为匹配的类生成代理对象--> 19 <aop:aspectj-autoproxy proxy-target-class="true" /> 20 21 22 <!--导入资源--> 23 <util:properties location="classpath:db.properties" local-override="true" id="db"/> 24 <!--配置C3P0数据源--> 25 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 26 <property name="driverClass" value="#{db.driverClass}"/> 27 <property name="jdbcUrl" value="#{db.jdbcUrl}"/> 28 <property name="user" value="#{db.user}"/> 29 <property name="password" value="#{db.password}"/> 30 31 <property name="initialPoolSize" value="#{db.initialPoolSize}"/> 32 <property name="maxPoolSize" value="#{db.maxPoolSize}"/> 33 </bean> 34 35 <!--配置jdbcTemplate的Bean--> 36 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 37 <property name="dataSource" ref="dataSource"/> 38 </bean> 39 40 <!--具名jdbc模版Bean--> 41 <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> 42 <constructor-arg name="dataSource" value="#{dataSource}"/> 43 </bean> 44 45 <!--配置事务管理器--> 46 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 47 <property name="dataSource" value="#{dataSource}"/> 48 </bean> 49 50 <!--启用事务注解--> 51 <tx:annotation-driven transaction-manager="transactionManager" /> 52 53 54 55 </beans>

猜你喜欢

转载自www.cnblogs.com/kill-9/p/9651771.html