猪呢 2014-05-24 15:37
浏览 219
已采纳

mybatis 事务相关问题

使用了mybatis后,比如有相关的增删改,这些都是与事务相关的,但是使用mybatis,就是一个接口,接口对应的配置文件,service再去调用这个接口,增删改都是与事务有关,怎么体现事务呢?我觉得我在写程序的过程中好像没有用到事务, 求解

  • 写回答

3条回答 默认 最新

  • 征服.刘华强 2014-05-25 21:10
    关注

    一般使用Mybaits也就这么几种情况。
    (1)单独使用Mybatis不与Spring集成,那么应该这么使用,最原始的方式。
    [code="java"] //这里要传false 手动事务
    SqlSession session = sqlSessionFactory.openSession(false);
    try {
    //插入A表
    //修改B表
    session.commit();
    } catch (Exception e) {
    session.rollback();
    } finally {
    session.close();
    }[/code]
    (2)与Spring集成使用,但是没有将事务托管给Spring,一般都是使用SqlSessionTemplate这个类,这种情况在Mybatis执行增删改查以后Mybatis会自动提交事务,关闭session。
    [code="java"]
    private class SqlSessionInterceptor implements InvocationHandler {
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    final SqlSession sqlSession = getSqlSession(
    SqlSessionTemplate.this.sqlSessionFactory,
    SqlSessionTemplate.this.executorType,
    SqlSessionTemplate.this.exceptionTranslator);
    try {
    Object result = method.invoke(sqlSession, args);
    if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
    // force commit even on non-dirty sessions because some databases require
    // a commit/rollback before calling close()
    sqlSession.commit(true);
    }
    return result;
    } catch (Throwable t) {
    Throwable unwrapped = unwrapThrowable(t);
    if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
    Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
    if (translated != null) {
    unwrapped = translated;
    }
    }
    throw unwrapped;
    } finally {
    closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
    }
    }
    }
    [/code]

    (3)与Spring集成使用,并且使用了Spring的事物上下文,那么事物会由Spring管理,这与hibernate与Spring集成的事物没有区别,Spring会管理事物。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?