附录: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;
	}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐