ssm集成mybatis提交commit异常问题

ssm集成mybatis提交commit异常问题

Manual commit is not allowed over a Spring managed SqlSession 
Manual close is not allowed over a Spring managed SqlSession 

出现这种异常是因为spring在管理sqlsession对象的时候使用了代理类,通过这个代理类来实现对所有的事物实现提交以及关闭

跟踪源码我们可以发现

    //这是我调用的方法,现在进入session的insert的方法内
    public boolean insert(Users users) {
        SqlSession session = super.getSqlSession();
        System.out.println(session);
        int insert = session.insert("com.cc.dao.UserDao.insert", users);
        return insert>0?true:false;
    }

//发现原来是用代理类实现的,接着跟踪
  @Override
  public int insert(String statement, Object parameter) {
    return this.sqlSessionProxy.insert(statement, parameter);
  }
  
  //这是这个代理类的创建方式,于是,找到了SqlSessionInterceptor这个类
  this.sqlSessionProxy = (SqlSession) newProxyInstance(
        SqlSessionFactory.class.getClassLoader(),
        new Class[] { SqlSession.class },
        new SqlSessionInterceptor());
    
    
    
    //这就是这个代理类的invoke方法,可以看到,他确实是帮我们实现了commit方法以及close方法
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      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) {
          // release the connection to avoid a deadlock if the translator is no loaded. See issue #22
          closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
          sqlSession = null;
          Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
          if (translated != null) {
            unwrapped = translated;
          }
        }
        throw unwrapped;
      } finally {
        if (sqlSession != null) {
          closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
        }
      }
    }

猜你喜欢

转载自blog.csdn.net/momomoniqwer/article/details/78567692