日期:2014-05-16  浏览次数:20405 次

九、同时使用jdbcTemplate和hibernate时,事务控制

<!--Hibernate TransactionManager-->
??? <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
??? ??? <property name="sessionFactory" ref="sessionFactory" />
??? </bean>

?

<!-- 以AspectJ方式 定义 AOP -->
??? <aop:config>
??? ??? <aop:pointcut id="cuccpayManagerOperations" expression="execution(* com.ygtime.man.busi..*Manager.*(..))" />
??? ??? <aop:pointcut id="coreManagerOperations" expression="execution(* com.ygtime.man.core..*Manager.*(..))" />
??? ??? <aop:pointcut id="securityManagerOperations" expression="execution(* com.ygtime.man.security..*Manager.*(..))" />
??? ??? <aop:pointcut id="logManagerOperations" expression="execution(* com.ygtime.man.log..*Manager.*(..))" />
??? ??? <aop:advisor advice-ref="txAdvice" pointcut-ref="cuccpayManagerOperations" />
??? ??? <aop:advisor advice-ref="txAdvice" pointcut-ref="coreManagerOperations" />
??? ??? <aop:advisor advice-ref="txAdvice" pointcut-ref="securityManagerOperations" />
??? ??? <aop:advisor advice-ref="txAdvice" pointcut-ref="logManagerOperations" />
??? </aop:config>

??? <!-- 基本事务定义,使用transactionManager作事务管理,默认get*方法的事务为readonly,其余方法按默认设置.默认的设置请参考Spring文档事务一章. -->
??? <tx:advice id="txAdvice" transaction-manager="transactionManager">
??? ??? <tx:attributes>
??? ??? ??? <tx:method name="get*" read-only="true" propagation="REQUIRED" />
??? ??? ??? <tx:method name="find*" read-only="true" propagation="REQUIRED" />
??? ??? ??? <tx:method name="query*" read-only="true" propagation="REQUIRED" />
??? ??? ??? <tx:method name="show*" read-only="true" propagation="REQUIRED" />
??? ??? ??? <tx:method name="list*" read-only="true" propagation="REQUIRED" />
??? ??? ??? <tx:method name="*" propagation="REQUIRED"
??? ??? ??? ??? rollback-for="com.ygtime.man.core.exception.BusinessException" />
??? ??? </tx:attributes>
??? </tx:advice>

?

public class ShopInfoManagerImpl{

?

??? @Override
??? public void depositReturn(long shopId, double money, SysUser sysUser) {
??? ?? ?
??? ?? ?int deposit = jdbcTemplate.queryForInt(
??? ?? ??? ?"select deposit from TM_PAY_SHOP_INFO where id=? for update", new Object[] { shopId });
??? ?? ?
??? ?? ?if (new Money(money).getCent() > deposit) {
??? ?? ??? ?throw new BusinessException("充值回退失败:余额不足");
??? ?? ?} else {
??? ?? ??? ?
??? ?? ??? ?jdbcTemplate.update("update TM_PAY_SHOP_INFO set deposit=? where id=?", new Object[] {
??? ?? ??? ??? ??? ?deposit - new Money(money).getCent(), shopId });
??? ?? ??? ?
??? ?? ?}
??? ?? ?
??? ?? ?saveJournal(shopId, money, sysUser, DepositChangeJournal.CHANGE_TYPE_RETURN,
??? ?? ??? ?DepositChangeJournal.CHANGE_STATUS_SUCCESS);
??? ?? ?
??? ?? ?int i = 1 / 0;
??? ?? ?System.out.println(i);
??? ?? ?
??? } ??

}

?

那么depositReturn方法里面的jdbcTemplate的操作,都在事务控制之类。

在执行int i = 1 / 0;System.out.println(i);之后,所有都会回滚。

而不再是每执行一次jdbcTemplate都会自动提交jdbcTemplate的事务。