springboot开启事务
springboot开启事务手动事务TransactionTemplate编程式事务
·
一、加@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;
}
更多推荐
已为社区贡献12条内容
所有评论(0)