spring事务笔记

一、先看栗子:

@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = { RuntimeException.class, Error.class,
			Exception.class })
	@Override
	public void test1() throws Exception {
		for (long i = 0; i < 2; i++) {
			insert(i);
		}

		arService.test1();

		// throw new RuntimeException("aa");

		throw new IOException("aa");
	}

arService:

	@Transactional
	public void test1() throws Exception {
		for (long i = 0; i < 2; i++) {
			insert(i);
		}

		// ok,全部回滚
		// throw new RuntimeException("aa");

		// ok,全部回滚
		//throw new IOException("aa");
	}

以上事务可以正常回滚。

那么问题来了:
1。上面为什么加rollbackFor呢?


  Open Declaration   Class<? extends Throwable>[] org.springframework.transaction.annotation.Transactional.rollbackFor() : {}


Defines zero (0) or more exception classes, which must besubclasses of Throwable, indicating which exception types must causea transaction rollback. 

By default, a transaction will be rolling back on RuntimeException and Error but not on checked exceptions (business exceptions). See org.springframework.transaction.interceptor.DefaultTransactionAttribute.rollbackOn(Throwable)for a detailed explanation. 

This is the preferred way to construct a rollback rule (in contrast to rollbackForClassName), matching the exception class and its subclasses. 

Similar to org.springframework.transaction.interceptor.RollbackRuleAttribute.RollbackRuleAttribute(Class clazz).
See Also:rollbackForClassNameorg.springframework.transaction.interceptor.DefaultTransactionAttribute.rollbackOn(Throwable)

相信都能看懂了吧。默认情况下事务只回滚RuntimeException and Error两种异常,IOException异常不能回滚,因为IOException是非运行时异常。如下图:
在这里插入图片描述
2。注意两点:
1)。执行过程中的 runtime exception 会由 spring 捕获,并回滚之前执行的 sql
2)。在 Transactional 内部,不要 try catch,事务才能生效。

二、再看栗子:

@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = { RuntimeException.class, Error.class,
			Exception.class })
	@Override
	public void test1() throws Exception {
		for (long i = 0; i < 2; i++) {
			insert(i);
		}

		ApplicationContextUtil.getBean(this.getClass()).test3();

		// throw new BusinessException("aa");

		throw new IOException("aa");
	}
	
	@Transactional
	public void test3() throws Exception {
		insert();
	}

是不是发现调用test3方法有点特别?

参读一下Spring之AOP注解失效原因和解决方法

在spring 中使用 @Transactional 、 @Cacheable 或 自定义 AOP 注解时,会发现个问题:在对象内部的方法中调用该对象的其他使用AOP注解的方法,被调用方法的AOP注解失效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值