通过实现接口:TransactionCallback
该模板类也需要在bean中配置TranscationManger。
<!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置事务模板对象--> <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager" ref="transactionManager"></property> </bean> <bean id="accountService" class="com.czy.service.impl.AccountServiceImpl"> <property name="dao" ref="accountDao"></property> <property name="transactionTemplate" ref="transactionTemplate"></property> </bean>
package com.czy.service.impl; import com.czy.dao.AccountDao; import com.czy.domain.Account; import com.czy.service.AccountService; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; public class AccountServiceImpl implements AccountService { private AccountDao dao; private TransactionTemplate transactionTemplate; public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } public void setDao(AccountDao dao) { this.dao = dao; } public Account findAccountById(Integer accountId) { return dao.findAccountById(accountId); } public void transfer(String sourceName, String targetName, Float money) { transactionTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus transactionStatus) { Account source = dao.findAccountByName(sourceName); Account target = dao.findAccountByName(targetName); source.setMoney(source.getMoney() - money); dao.updateAccount(source); int i = 1/0; target.setMoney(target.getMoney() + money); dao.updateAccount(target); return null; } }); } }