猪呢 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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改