spring的事务管理,本文的例子是:比如你需要网购一本书,卖书的那一方有库存量以及书的价格,你有账户余额。回想我们在编程中要实现买书这样的功能,由于你的账户表和书的库存量表肯定不是同一张数据库表,所以必定会有一个先后,要么先将账户余额扣除书的价格,紧接着将书的库存量减一,要么反过来。那么问题来了,假如我们先将你的账户余额减掉,然后发现书的库存不足,这时怎么办呢,这就需要事务了,当我们发现书的库存不足时就要回滚事务,将你的余额返回去。只要配置了事务,发生了异常,就回滚。这就是事务的回滚。注:新人理解,如有错误,望指正,谢谢。
配置文件applicationContext.xml:
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:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> 10 11 <!-- 导入资源文件 --> 12 <context:property-placeholder location="classpath:jdbc.properties"/> 13 14 <!-- 配置c3p0数据源 --> 15 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 16 <property name="user" value="${user}"></property> 17 <property name="password" value="${password}"></property> 18 <property name="driverClass" value="${driverClass}"></property> 19 <property name="jdbcUrl" value="${jdbcUrl}"></property> 20 21 <property name="initialPoolSize" value="${initPoolSize}"></property> 22 <property name="maxPoolSize" value="${maxPoolSize}"></property> 23 </bean> 24 25 <!-- 配置自动扫描的包 --> 26 <context:component-scan base-package="spring"></context:component-scan> 27 28 <!-- 配置spring 的JdbcTemplate --> 29 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 30 <property name="dataSource" ref="dataSource"></property> 31 </bean> 32 33 <!-- 配置事务管理器 --> 34 <bean id="transactionManager" 35 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 36 <property name="dataSource" ref="dataSource"></property> 37 </bean> 38 39 <!-- 启用事务注解 --> 40 <tx:annotation-driven transaction-manager="transactionManager"/> 41 42 43 </beans>