Spring5 源码阅读笔记(4.2)编程式事务 TransactionTemplate

本文探讨了注解式事务在方法执行时间过长时的局限性,及编程式事务通过TransactionTemplate提供的更灵活的事务管理方式,深入解析其源码执行流程。

注解式事务的不足

当方法执行的时间过长,方法里的某些操作并不需要被包括在事务内的时候,用 @Transactional 就不太好了。因为事务一直得不到提交或回滚会一直占用连接。

编程式事务

@Autowired
private TransactionTemplate transactionTemplate;


public void method() {

    Integer execute = transactionTemplate.execute(status -> {
        //业务代码
    });

    if (execute == 0) {
    	//如果执行不成功,可以继续调 method()
       //method();
    }
}

跟源码

@Override
@Nullable
public <T> T execute(TransactionCallback<T> action) throws TransactionException {
	Assert.state(this.transactionManager != null, "No PlatformTransactionManager set");

	if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
		return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
	}
	else {
														//开启事务,见4.1
		TransactionStatus status = this.transactionManager.getTransaction(this);
		T result;
		try {
							//调匿名类里的方法 excute(status->{})
			result = action.doInTransaction(status);
		}
		catch (RuntimeException | Error ex) {
			// Transactional code threw application exception -> rollback
			//回滚
			rollbackOnException(status, ex);
			throw ex;
		}
		catch (Throwable ex) {
			// Transactional code threw unexpected exception -> rollback
			rollbackOnException(status, ex);
			throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
		}
		//提交
		this.transactionManager.commit(status);
		return result;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值