【SSM-Spring】Spring声明式事务

1.在context中配置事务管理器

(1)首先在头上加:
  xmlns:tx="http://www.springframework.org/schema/tx"

   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
  <!-- 2  配置事务管理器-->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
   </bean>
    <!-- 3   启用事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager" />

2.添加事务注解

//2 添加事务注解
@Transactional
@Override
public void purchase(String username, String isbn) {
    int price =  bookShopDao.findBookPriceByIsbn(isbn);
    bookShopDao.updateBookStock(isbn);
    bookShopDao.updateUserAccount(username,price);
}

3.Test

@Test
public void TestBookShopService(){
    bookShopService.purchase("AA","1001");
}

未加事务之前是余额不足也减库存
【SSM-Spring】Spring声明式事务
都是单独的sql语句执行,减库存时只判断库存,而在代码块上加了
@Transactional,就是整体为一个事务 原子性操作要么都做要么都不做