最终一步,用到测试是否有事务功能代码:
public class AccountServiceImpl implements AccountService{ public void txTransfer(AccountDao accountDao,String out,String in,Double money)throws Exception{ accountDao.outMoney(out,money); int i=1/0; accountDao.inMoney(in,money); } } 控制器类页面: public ModelAndView handleMin(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mv; mv= new ModelAndView(moneyinView ); accountService.txTransfer(accountDao ,"aaa" , "bbb" , 200d ); return mv; }
关键的插入代码:
public void outMoney (String out,Double money){ System. out.print("impl000000" +out);System.out.print( "impt11111"+money); String sql= "update Account account set account.money= account.money-? where account.name=?"; Session sess= null; sess= this.getSession(); Query q = sess.createQuery(sql); q.setDouble(0, money); q.setString(1, out); q.executeUpdate(); public void inMoney(String in,Double money){ String sql= "update Account account set account.money=account.money+ ? where account.name=?"; Session sess= null; sess= this.getSession(); Query q = sess.createQuery(sql); q.setDouble(0, money); q.setString(1, in); q.executeUpdate(); }
services.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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id= "transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" > <property name="sessionFactory" > <ref bean="sessionFactory" /> </property> </bean> <bean id= "txProxyTemplate" abstract ="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" > <property name="transactionManager" > <ref bean="transactionManager" /> </property> <property name="transactionAttributes" > <props> <prop key="tx*" >PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE,timeout_200,-Exception</prop > </props> </property> </bean> <bean id= "accountService" parent ="txProxyTemplate"> <property name="target" > <bean class="com.test.service.impl.AccountServiceImpl" /> </property> </bean> </beans>
注:
PROPAGATION : 事务的传播行为
ISOLATION : 事务的隔离级别
timeout : 事务的超时时间
-Exception : 发生哪些异常回滚
+Exception : 发生哪些异常不回滚
readOnly : 只读