01|核心类

  • SqlSessionFactoryBuilder:负责构建SqlSessionFactory
  • SqlSessionFactory:负责构建SqlSession
  • SqlSession:mybatis操作数据库的顶层接口
  • Executor:执行增删改查的具体执行器
  • ParameterHandler:参数解析器
  • StatementHandler:Statement的处理器
  • ResultSetHandler:结果集处理器
  • Configuration:全局配置类
  • MappedStatement:映射信息描述类

    02|配置解析

    ```java public class SqlSessionFactoryBuilder{ public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    1. XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
    2. return build(parser.parse());
    } }

public class XMLConfigBuilder{ public Configuration parse() { if (parsed) { throw new BuilderException(“Each XMLConfigBuilder can only be used once.”); } parsed = true; // 解析XML配置文件中的所有配置属性并存入Configuration对象中 parseConfiguration(parser.evalNode(“/configuration”)); return configuration; }

private void parseConfiguration(XNode root) { try { //依次解析所有配置项信息 propertiesElement(root.evalNode(“properties”)); Properties settings = settingsAsProperties(root.evalNode(“settings”)); loadCustomVfs(settings); loadCustomLogImpl(settings); typeAliasesElement(root.evalNode(“typeAliases”)); pluginElement(root.evalNode(“plugins”)); objectFactoryElement(root.evalNode(“objectFactory”)); objectWrapperFactoryElement(root.evalNode(“objectWrapperFactory”)); reflectorFactoryElement(root.evalNode(“reflectorFactory”)); settingsElement(settings); environmentsElement(root.evalNode(“environments”)); databaseIdProviderElement(root.evalNode(“databaseIdProvider”)); typeHandlerElement(root.evalNode(“typeHandlers”)); // 解析mapper配置信息,并封装为MappedStatement放入Configuration对象中 // MapperdStatement对象中包含的sql语句执行的所有细节信息 mapperElement(root.evalNode(“mappers”)); } catch (Exception e) { throw new BuilderException(“Error parsing SQL Mapper Configuration. Cause: “ + e, e); } } }

  1. 当配置解析完毕,有关mybatis所需的所有配置项项目全部存入到了Configuration对象当中。
  2. <a name="Mshpl"></a>
  3. ## 03|SQL执行流程
  4. SqlSession.selectList()为例进行源码分析
  5. ```java
  6. @Test
  7. public void query() throws IOException {
  8. final SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
  9. final SqlSession sqlSession = factory.openSession();
  10. final List<Object> results = sqlSession.selectList("statement id");
  11. }

SqlSession默认实现类为DefaultSqlSession

  1. public class DefaultSqlSession implements SqlSession {
  2. @Override
  3. public <E> List<E> selectList(String statement) {
  4. return this.selectList(statement, null);
  5. }
  6. @Override
  7. public <E> List<E> selectList(String statement, Object parameter) {
  8. return this.selectList(statement, parameter, RowBounds.DEFAULT);
  9. }
  10. @Override
  11. public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  12. try {
  13. // 根据statementid从configuration配置中获取对应的MapperdStatement对象
  14. MappedStatement ms = configuration.getMappedStatement(statement);
  15. // 调用Executor执行具体的查询逻辑
  16. return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  17. } catch (Exception e) {
  18. throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
  19. } finally {
  20. ErrorContext.instance().reset();
  21. }
  22. }
  23. }

Executor拥有一个抽象子类BaseExecutor,Mybatis此处使用模版设计模式在BaseExecutor中封装一些列模版方法

  1. public abstract class BaseExecutor implements Executor {
  2. @Override
  3. public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  4. ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
  5. if (closed) {
  6. throw new ExecutorException("Executor was closed.");
  7. }
  8. if (queryStack == 0 && ms.isFlushCacheRequired()) {
  9. clearLocalCache();
  10. }
  11. List<E> list;
  12. try {
  13. queryStack++;
  14. // 尝试从缓存中查找数据,如存在则不再从数据库查询
  15. list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
  16. if (list != null) {
  17. handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
  18. } else {
  19. // 从数据库获取数据,调用模版方法,由子类去实现
  20. list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
  21. }
  22. } finally {
  23. queryStack--;
  24. }
  25. if (queryStack == 0) {
  26. for (DeferredLoad deferredLoad : deferredLoads) {
  27. deferredLoad.load();
  28. }
  29. // issue #601
  30. deferredLoads.clear();
  31. if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
  32. // issue #482
  33. clearLocalCache();
  34. }
  35. }
  36. return list;
  37. }
  38. private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  39. List<E> list;
  40. localCache.putObject(key, EXECUTION_PLACEHOLDER);
  41. try {
  42. list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
  43. } finally {
  44. localCache.removeObject(key);
  45. }
  46. localCache.putObject(key, list);
  47. if (ms.getStatementType() == StatementType.CALLABLE) {
  48. localOutputParameterCache.putObject(key, parameter);
  49. }
  50. return list;
  51. }
  52. protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
  53. throws SQLException;
  54. }

BaseExecutor的默认实现类为SimpleExecutor

  1. public class SimpleExecutor extends BaseExecutor {
  2. @Override
  3. public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  4. Statement stmt = null;
  5. try {
  6. Configuration configuration = ms.getConfiguration();
  7. // 创建StatementHandler,此处创建的是RoutingStatementHadnler,会依据StatementType创建对应的StatementHandler
  8. StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
  9. stmt = prepareStatement(handler, ms.getStatementLog());
  10. // 真正执行查询操作
  11. return handler.query(stmt, resultHandler);
  12. } finally {
  13. closeStatement(stmt);
  14. }
  15. }
  16. }
  17. public class SimpleStatementHandler extends BaseStatementHandler {
  18. @Override
  19. public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
  20. String sql = boundSql.getSql();
  21. statement.execute(sql);
  22. // 返回由ResultSetHandler处理之后的查询结果
  23. return resultSetHandler.handleResultSets(statement);
  24. }
  25. }