spring_声明式事务: @Transactional

  例子、


  <?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:tx="http://www.springframework.org/schema/tx"
   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-4.0.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<!--扫包-->
	<context:component-scan base-package="com.apcstudy.tx"></context:component-scan>

	<!--加载properties的文件-->
	<context:property-placeholder location="classpath:conf/dbconfig.properties" />

	<!--  配置数据源-->
	<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
		<property name="driverClass" value="${jdbc.driverClass}" />
	</bean>

	<!-- 配置JdbcTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="pooledDataSource" />
	</bean>

	<!--事务控制:事务切面-->
	<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 控制住数据源 -->
		<property name="dataSource" ref="pooledDataSource" />
	</bean>
	<!--2:开启基于注解的事务控制模式;依赖tx名称空间  -->
	<tx:annotation-driven transaction-manager="tx" />
	<!--3:给事务方法加注解@Transactional  
  @Service
  public class BookService {

          @Autowired
          private BookDao bookDao;

          /**
           *  结账;传入哪个用户买了哪本书
           * @param username
           * @param isbn
           */
          @Transactional
          public void checkout(String username,String isbn){
              //1、减库存
              bookDao.updateStock(isbn);

              int price = bookDao.getPrice(isbn);
              //2、减余额
              bookDao.updateBalance(username,price);
        }
    }
posted @ 2021-04-15 15:18  jock_javaEE  阅读(49)  评论(0编辑  收藏  举报