4年来一直在ssi中用spring控制事物。这回把spring+ibatis摘出来吧,以供不时之需。
applicationContext.xml
<!-- spring事务管理 方法一--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <aop:config> <aop:pointcut id="serviceOperation" expression="execution(* com.*.service.*.*(..))" /> <aop:advisor pointcut-ref="serviceOperation" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" rollback-for="Exception" /> <tx:method name="save*" rollback-for="Exception" /> <tx:method name="update*" rollback-for="Exception" /> <tx:method name="delete*" rollback-for="Exception" /> <tx:method name="*" read-only="true" rollback-for="Exception" /> </tx:attributes> </tx:advice>
主要java代码:
public void insertAccounts(List<Account> accountList) { for (int i = 0; i < accountList.size(); i++) { System.out.println(""+i); if(i==2){ //注释到就可以全部插入,否则spring的事物会让他们全部不插入,ACID int s=2/0;//抛出异常 } this.accountDao.insertAccount(accountList.get(i)); } }
另外,附件也上传了一份jdbc的事物源代码,这个是复制自别人的的,可惜忘了地址,抱歉。