Spring编程式事务的使用

  • 引入事务管理器
@Autowired
TransactionTemplate transactionTemplate;

@Autowired
PlatformTransactionManager transactionManager;
  • 使用方式1
//开启事务保存数据
boolean result = transactionTemplate.execute(new TransactionCallback<Boolean>() {
    @Override
    public Boolean doInTransaction(TransactionStatus status) {
        try {
            // TODO something
        } catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
            status.setRollbackOnly();
            logger.error(e.getMessage(), e);
            return false;
        }
        return true;
    }
});
  • 使用方式2
/**
 * 定义事务
 */
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setReadOnly(false);
//隔离级别,-1表示使用数据库默认级别
def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = transactionManager.getTransaction(def);
try {
    //TODO something
     transactionManager.commit(status);
} catch (Exception e) {
    transactionManager.rollback(status);
    throw new InvoiceApplyException("异常失败");
}
  • 使用方式3
SqlSession sqlSession = null;
try {
    sqlSession = otInvSqlSessionFactory.openSession(ExecutorType.BATCH, true);
    XXXXXMapper xXxxMapper = sqlSession.getMapper(XXXXXMapper.class);
    sqlSession.commit();
}catch(Exception e){
    if (null != otInvSqlSession) {
        sqlSession.rollback(true);
        logger.error("数据回滚", e);
    }
}finally {
    if (null != sqlSession) {
        sqlSession.clearCache();
        sqlSession.close();
    }
}
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值