编程式的事务管理
1.配置事务管理器(以JdbcDataSource为例)
将dataSource连接池注入管理器中,这时因为jdbc进行管理时需要获得连接对象,然后用connection.setAutoCommit(false)使其不自动提交,<br>执行完后要conmmit,有异常的话要rollback。 能获取这个连接的就是dataSource连接池,而DataSourceTransactionManager事务管理器<br>是真正进行事务管理的类,而连接池又能获取到连接对象,所以要将其注入。
<!-- 配置事务管理器 --><br><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><br> <property name="dataSource" ref="dataSource"/><br></bean>
2.配置事务管理模板
<bean id = "transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"><br> <property name="transactionManager" ref="transactionManager"/><br></bean><br>
3.在Service中注入模板
<!-- service层注入transactionTemplate --><br><bean id = "accountService" class="com.cfx.service.impl.AccountServiceImpl"><br> <property name="transactionTemplate" ref="transactionTemplate"></property><br></bean><br>
private TransactionTemplate transactionTemplate;<br> <br>public void setTransactionTemplate(TransactionTemplate transactionTemplate) {<br> this.transactionTemplate = transactionTemplate;<br> }<br> <br> @Override<br> public void transfer(String out, String in, Double money) {<br> transactionTemplate.execute(new TransactionCallbackWithoutResult(){<br> @Override<br> protected void doInTransactionWithoutResult(TransactionStatus arg0) {<br> accountDao.outMoney(out, money);<br> int i = 1/0;//若不进行事务管理,出现错误,outMoney()将会执行。<br> accountDao.inMoney(in, money);<br> }<br>
声明式的事务管理
简介
Spring集成了很多内置的事务管理器,最常用两种便是DataSourceTransactionManager和HibernateTransactionManager:<br>DataSourceTransactionManager:用于Spring JDBC抽象框架、iBATIS或MyBatis框架的事务管理;<br>HibernateTransactionManager:用于集成Hibernate框架时的事务管理.
基于AspectJ的方式<br>
配置事务管理器..(切面)<br> <tx:advice id="accountAdvice" transaction-manager="transactionManager"> <br> <!--配置事务传播性,隔离级别以及超时回滚等问题 --> <br> <tx:attributes> <br> <tx:method name="save*" propagation="REQUIRED" /> <br> <tx:method name="del*" propagation="REQUIRED" /> <br> <tx:method name="update*" propagation="REQUIRED" /> <br> <tx:method name="add*" propagation="REQUIRED" /> <br> <tx:method name="*" rollback-for="Exception" /> <br> </tx:attributes> <br> </tx:advice> <br> <aop:config> <br> <!--配置切点 与切面--> <br> <aop:pointcut id="services" expression="execution(* com.cfx.service.*.*(..))" /> <br> <aop:advisor pointcut-ref="services" advice-ref="accountAdvice" /> <br> </aop:config><br>因为采用切面的方式,所以其他位置将不需要改变。