Spring 框架基础(05):事务管理机制,和实现方式 (2)

+Exception 异常提交

2、演示案例 @Service public class UserAccountServiceImpl01 extends JdbcDaoSupport implements UserAccountService01 { @Override public void remittance(String remitTer, String receiver, int money) { outMoney(remitTer,money); System.out.println(1/0); innerMoney(receiver,money); } private void outMoney (String remitTer, int money){ String outSql = "update user_account set money = money - ? where username = ?"; this.getJdbcTemplate().update(outSql, money ,remitTer); } private void innerMoney (String receiver, int money){ String inSql = "update user_account set money = money + ? where username = ?"; this.getJdbcTemplate().update(inSql, money,receiver); } } 3、测试代码 public class Tx_Test_02 { @Test public void test1 (){ String xmlPath = "spring-jdbc-tx-02.xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlPath); UserAccountService01 accountService = (UserAccountService01) context.getBean("proxyAccountService"); accountService.remittance("jack","tom",1000); } } 四、XML配置事务

首先配置事务管理器,然后配置事务属性,最后基于AOP编程配置事务切入点。

1、核心配置 <!-- 配置事物管理器 --> <bean> <property ref="dataSource" /> </bean> <!-- 配置转账接口 --> <bean> <property ref="jdbcTemplate" /> </bean> <!-- 配置事物详情 --> <tx:advice transaction-manager="txManager"> <tx:attributes> <tx:method propagation="REQUIRED" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 事务切入点,基于AOP编程 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.spring.mvc.service.UserAccountService01.*(..))"/> </aop:config> 五、基于事务注解

配置事务管理器,并启动事务注解的支持,在目标类或目标方法添加@Transactional核心注解即可。

1、核心配置 <!-- 配置事物管理器 --> <bean> <property ref="dataSource" /> </bean> <!-- 支持事务注解 --> <tx:annotation-driven transaction-manager="txManager" /> 2、注解用法

注解写在接口方法上,或者接口实现的方法上效果一样。

public interface UserAccountService02 { @Transactional(rollbackFor = Exception.class) void remittance(String remitTer, String receiver, int money) ; } 六、源代码地址 GitHub·地址 https://github.com/cicadasmile/spring-mvc-parent GitEE·地址 https://gitee.com/cicadasmile/spring-mvc-parent

Spring 框架基础(05):事务管理机制,和实现方式

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzsswf.html