Mybatis走进源码世界(二)

(1)首先是如何构建sqlSessionFactory的?

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      //构建一个configuration
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      //返回一个DefaultSqlSessionFactory
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        inputStream.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
}
public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
}

(2)获取sqlSession对象

//最终是进入了这个方法之中的
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    //事务先不管
    Transaction tx = null;
    try {
      //得到mybatisConfig.xml中的environment
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
public class DefaultSqlSession implements SqlSession {
    //configuration核心
    private final Configuration configuration;
    //真正执行sql的类
    private final Executor executor;
}

(3)通过sqlSession的getMapper(Class)获得Mapper的代理对象。

  @Override
  public <T> T getMapper(Class<T> type) {
       //交给configuration去做(委派模式)
       return configuration.<T>getMapper(type, this);
  }
  //交给mapperRegistry去做
  public boolean hasMapper(Class<?> type) {
       return mapperRegistry.hasMapper(type);
  }

   @SuppressWarnings("unchecked")
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    //knownMappers是一个map,里面装的是:以class为key,factory为value
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      //关键代码:创建mapper的代理类
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    //生成代理子类
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }


  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

(4)获得了mapperProxy对象了,如何调用mapper的方法

//显然,获得是mapperProxy对象,那么就会调用invoke方法。
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //其实不会走到这里
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //从缓存当中取出MapperMethod
    //存放了接口当前的方法,属于哪种类型,返回类型属于哪种
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //关键点开始了
    return mapperMethod.execute(sqlSession, args);
  }
private MapperMethod cachedMapperMethod(Method method) {
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());    
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
}
public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    //判断是增删改查的哪一种
    if (SqlCommandType.INSERT == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.insert(command.getName(), param));
    } else if (SqlCommandType.UPDATE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.update(command.getName(), param));
    } else if (SqlCommandType.DELETE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.delete(command.getName(), param));
    } else if (SqlCommandType.SELECT == command.getType()) {
      //判断select语句的返回类型:就先看个最简单的,selectOne
      if (method.returnsVoid() && method.hasResultHandler()) {
        executeWithResultHandler(sqlSession, args);
        result = null;
      } else if (method.returnsMany()) {
        result = executeForMany(sqlSession, args);
      } else if (method.returnsMap()) {
        result = executeForMap(sqlSession, args);
      } else {
        Object param = method.convertArgsToSqlCommandParam(args);
        //关键地方:继续进入
        result = sqlSession.selectOne(command.getName(), param);
      }
    } else {
      throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName() 
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }
//最终是进入了这个selectList里面,然后通过get(0)来作为selectOne
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      //又在此利用executor去作为真正的数据库操作
      List<E> result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
      return result;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
//最后是进入这里
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    //二级缓存
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, parameterObject, boundSql);
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578. Query must be not synchronized to prevent deadlocks
        }
        return list;
      }
    }
    //没有二级缓存时,是进入这里
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }
//这里开始就是重点了 
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) throw new ExecutorException("Executor was closed.");
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List<E> list;
    try {
      queryStack++;
      //这里是一个缓存,一级缓存也就是sqlSession的缓存,满足的条件是:sql语句必须一模一样,参数也必须一样,
      //localcache是一个hashMap,是以sql和参数作为key
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        //首次查询就是进入这里
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      deferredLoads.clear(); // issue #601
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        clearLocalCache(); // issue #482
      }
    }
    return list;
  }
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    //这里有一个非常重要的思想,我想了很久都不知道为什么需要先put一次常量进入缓存,在查询之后又删除缓存的常量,又放入真正的缓存
    //这是为什么喃?
    //其实就是一个缓存击穿的一种解决思路
    /**
     * 假设一种场景,1000个线程同时使用一个sqlSession,那么假设并发访问一个sql,那么这样大量的线程就会进行数据库访问
     * 数据库效率就会低下甚至是崩溃
     * 这样的做法非常值得借鉴,不管有没有缓存,先放一个假的缓存进去,那么这样能够阻挡其他大部分的相同访问,然后再放入真正的缓存
     * 顺带跳过一下,再仔细研究一下mybatis是如何看待缓存和数据库一致的问题喃?
     * public void clearLocalCache() {
            if (!closed) {
              localCache.clear();
              localOutputParameterCache.clear();
            }
        }
     * 就是清空了缓存(二级缓存也是清空了的,但是没放出来),这样的思想也行,但是容易产生缓存过时的问题
     *   (删了缓存,还在写的时候,另外的线程访问了,写入了过时的缓存)
     * 这个地方就可以采取双删策略
     */  
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      localCache.removeObject(key);
    }
    //真正的缓存
    localCache.putObject(key, list);
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }


猜你喜欢

转载自blog.csdn.net/qq_40384690/article/details/81031218