Spring编程式事务配置,实现模拟转账过程
1.新建项目,配置相应jar包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.2.1.RELEASE</version> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <!-- c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>
2.新建数据表(模拟aa向bb转账200,模拟aa扣款后出现异常)
DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `money` double unsigned zerofill DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; INSERT INTO `account` VALUES ('1', 'aa', '1000'); INSERT INTO `account` VALUES ('2', 'bb', '1000'); INSERT INTO `account` VALUES ('3', 'cc', '1000');
3.配置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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- 编程式事务 --> <!-- 引入外部属性文件 --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc_driverClassName}" /> <property name="jdbcUrl" value="${jdbc_url}" /> <property name="user" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> </bean> <!-- 配置业务层 --> <!-- 开启annotation --> <context:annotation-config/> <context:component-scan base-package="cn.dx.spring.transaction.service" /> <context:component-scan base-package="cn.dx.spring.transaction.dao" /> <!-- JDBC模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入连接池对象 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 事务管理模板:Spring为了简化事务管理的代码而提供的类 --> <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager" ref="transactionManager" /> </bean> </beans>
4.配置log4j
#console log log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m%n #all log log4j.appender.DAILY_ALL=org.apache.log4j.DailyRollingFileAppender log4j.appender.DAILY_ALL.layout=org.apache.log4j.PatternLayout log4j.appender.DAILY_ALL.layout.ConversionPattern="%p %d{yyyy-MM-dd HH:mm:ss} %-50.50c(%L) - %m%n log4j.appender.DAILY_ALL.File=d:/myjava.log log4j.appender.DAILY_ALL.DatePattern='.'yyyy-MM-dd #logger #log4j.logger.org.springframework=INFO,CONSOLE #log4j.logger.org.hibernate=INFO,CONSOLE #log4j.logger.org.apache=INFO,CONSOLE log4j.rootLogger=INFO,CONSOLE,DAILY_ALL
5.配置jdbc.properties
jdbc_driverClassName=com.mysql.jdbc.Driver jdbc_url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8 jdbc_username=root jdbc_password=root
6.dao以及impl
package cn.dx.spring.transaction.dao; public interface AccountDao { /** * @param out 转出账户 * @param money 转出金额 */ void outMoney(String out,Double money); /** * @param in :传入账号 * @param money :转入金额 */ void inMoney(String in,Double money); }
package cn.dx.spring.transaction.dao.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import cn.dx.spring.transaction.dao.AccountDao; @Component("AccountDao") public class AccountDaoImpl implements AccountDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public void outMoney(String out, Double money) { String sql = "update account set money = money - ? where name = ?"; this.jdbcTemplate.update(sql,money,out); } @Override public void inMoney(String in, Double money) { String sql = "update account set money = money + ? where name = ?"; this.jdbcTemplate.update(sql,money,in); } }
7.service以及impl
package cn.dx.spring.transaction.service; /** * 转账Service * @author 大雄 * */ public interface AccountService { /** * * @param out:转出账户 * @param in:转入账户 * @param money:转账金额 */ void transfer(String out,String in,Double money); }
package cn.dx.spring.transaction.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; import cn.dx.spring.transaction.dao.AccountDao; import cn.dx.spring.transaction.service.AccountService; @Service("AccountService") public class AccountServiceImpl implements AccountService { @Autowired @Qualifier("AccountDao") private AccountDao accountDao; @Autowired private TransactionTemplate transactionTemplate; @Override public void transfer(final String out,final String in,final Double money) { this.transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { accountDao.outMoney(out, money); int i = 1/0; accountDao.inMoney(in, money); } }); } }
在这儿如果出现 1/0的话会出现异常,如果没有事务,则aa的钱会-200,而bb的钱不会+200.事务配置好后,在1/0异常后数据库aa和bb的钱不变
8.新建测试类
package cn.dx.myjava.spring.transaction; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.dx.spring.transaction.service.AccountService; /** * 编程式事务管理 * 转账测试 * @author 大雄 * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class Transtraction { //测试业务层的类 @Autowired @Qualifier("AccountService") private AccountService accountService; @Test public void transaction(){ this.accountService.transfer("aa", "bb", 200d); } }
运行transaction进行单元测试