springboot开启事务

附录:spring事务传播机制

一、加@Transactional注解

	// 默认是RuntimeException就回滚,传播机制为请求事务,REQUIRED
	@Transactional(rollbackFor = RollBackException.class,propagation = Propagation.REQUIRED)
	public Boolean execute(){
		try {
		//	代码
		} catch (Exception e) {
			log.error("xxxxxx",e);
			//回滚方式一:手动回滚
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			//回滚方式二:抛异常
			// throw new RollBackException("发生异常了肿么办!!!");
		}
		return true;
	}

二、手动事务

推荐的手动开启事务方式
	@Autowired
	private DataSourceTransactionManager dataSourceTransactionManager;
	@Autowired
	TransactionDefinition transactionDefinition;
	
	public Boolean execute(){
		// 手动开启事务
		TransactionStatus transactionStatus = null;
		try {
			//方式一:使用默认bean对象TransactionDefinition
			transactionStatus =dataSourceTransactionManager.getTransaction(transactionDefinition);
			//方式二:自己创建,可以设置事务传播机制,但一般都是使用PROPAGATION_REQUIRED。
			// DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			// def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
			//transactionStatus = dataSourceTransactionManager.getTransaction(def);
			// 代码逻辑 ..
			
			// 提交
			dataSourceTransactionManager.commit(transactionStatus);
		} catch (Exception e) {
			log.error("xxxxxx",e);
			if (ts != null) {
				dataSourceTransactionManager.rollback(ts);
			}
			throw new RollBackException("发生异常了肿么办!!!");
		}
		return true;
	}
另一种,使用TransactionTemplate.execute() 编程式事务
	@Autowired
	private TransactionTemplate transactionTemplate;

	public Boolean execute() {
		transactionTemplate.execute(new TransactionCallback<Object>() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				// 代码...
				
				// 除了发生异常之外,如果你的业务逻辑需要设置事务回滚,可以用这个
				if (true) {
					//方式一:设置属性
					status.setRollbackOnly();
					//方式二:抛异常
					// throw new RollBackException("发生异常了肿么办!!!");
				}
				return null;
			}
		});
		return true;
	}

  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值