Spring编程式事务的使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lsziri/article/details/80656600
  • 引入事务管理器
@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();
    }
}
展开阅读全文

没有更多推荐了,返回首页