猪呢 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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算