阅读MyBatis源码的一些个人理解

MyBatis原理分析

MyBatis工作流程简述

传统工作模式:

public static void main(String[] args) {

                 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

                 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);

                 SqlSession sqlSession = factory.openSession();

                 String name = "tom";

List<User>list=sqlSession.selectList("com.demo.mapper.UserMapper.getUserByName",params);

}

1、创建SqlSessionFactoryBuilder对象,调用build(inputstream)方法读取并解析配置文件,返回SqlSessionFactory对象

2、由SqlSessionFactory创建SqlSession 对象,没有手动设置的话事务默认开启

3、调用SqlSession中的api,传入Statement Id和参数,内部进行复杂的处理,最后调用jdbc执行SQL语句,封装结果返回。

使用Mapper接口:
由于面向接口编程的趋势,MyBatis也实现了通过接口调用mapper配置文件中的SQL语句

详细请自行http://baidu.com,本篇文章将不再过多介绍

原生MyBatis原理分析

初始化工作

解析配置文件

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

//这一行代码正是初始化工作的开始。

SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);

进入源码分析:

// 我们最初调用的build

public SqlSessionFactory build(InputStream inputStream) {

       //调用了重载方法

    return build(inputStream, null, null);

  }

// 调用的重载方法

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {

    try {

      //  XMLConfigBuilder是专门解析mybatis的配置文件的类

      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);

      //这里又调用了一个重载方法。parser.parse()的返回值是Configuration对象

      return build(parser.parse());

    } catch (Exception e) {

      throw ExceptionFactory.wrapException("Error building SqlSession.", e);

    }

  }

首先对Configuration对象进行介绍:

Configuration对象的结构和xml配置文件的对象几乎相同。

回顾一下xml中的配置标签有哪些:

properties(属性),settings(设置),typeAliases(类型别名),typeHandlers(类型处理器),objectFactory(对象工厂),mappers(映射器)等

Configuration也有对应的对象属性来封装它们

详细请浏览:https://blog.csdn.net/qq_44407005/article/details/114266779

也就是说,初始化配置文件信息的本质就是创建Configuration对象,将解析的xml数据封装到Configuration内部的属性中。

//在创建XMLConfigBuilder时,它的构造方法中解析器XPathParser已经读取了配置文件

//进入XMLConfigBuilder 中的 parse()方法。

public Configuration parse() {

    if (parsed) {

      throw new BuilderException("Each XMLConfigBuilder can only be used once.");

    }

    parsed = true;

    //parserXPathParser解析器对象,读取节点内数据,<configuration>MyBatis配置文件中的顶层标签

    parseConfiguration(parser.evalNode("/configuration"));

    //最后返回的是Configuration 对象

    return configuration;

}

//进入parseConfiguration方法

//此方法中读取了各个标签内容并封装到Configuration中的属性中。

private void parseConfiguration(XNode root) {

    try {

      //issue #117 read properties first

      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);

      // read it after objectFactory and objectWrapperFactory issue #631

      environmentsElement(root.evalNode("environments"));

      databaseIdProviderElement(root.evalNode("databaseIdProvider"));

      typeHandlerElement(root.evalNode("typeHandlers"));

      mapperElement(root.evalNode("mappers"));

    } catch (Exception e) {

      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);

    }

}

继续分析,初始化完毕后,我们就要执行SQL了:

//创建并返回SqlSession实例
public  static SqlSession createSqlSession(){
    return factory.openSession(false);
}

获得sqlSession

//进入openSession方法。

  public SqlSession openSession() {

      //getDefaultExecutorType()传递的是SimpleExecutor

    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);

  }

//进入openSessionFromDataSource

//ExecutorType Executor的类型,TransactionIsolationLevel为事务隔离级别,autoCommit是否开启事务

//openSession的多个重载方法可以指定获得的SeqSessionExecutor类型和事务的处理

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {

    Transaction tx = null;

    try {

      final Environment environment = configuration.getEnvironment();

      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);

      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);

      //根据参数创建指定类型的Executor

      final Executor executor = configuration.newExecutor(tx, execType);

      //返回的是DefaultSqlSession

      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();

    }

  }

执行sqlsession中的api

//进入selectList方法,多个重载方法。

public <E> List<E> selectList(String statement) {

    return this.selectList(statement, null);

}

public <E> List<E> selectList(String statement, Object parameter) {

    return this.selectList(statement, parameter, RowBounds.DEFAULT);

}

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {

    try {

      //根据传入的全限定名+方法名从映射的Map中取出MappedStatement对象

      MappedStatement ms = configuration.getMappedStatement(statement);

      //调用Executor中的方法处理

      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);

    } catch (Exception e) {

      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);

    } finally {

      ErrorContext.instance().reset();

    }

 }

继续源码中的步骤,进入 executor.query()

//此方法在SimpleExecutor的父类BaseExecutor中实现

public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {

        //根据传入的参数动态获得SQL语句,最后返回用BoundSql对象表示

    BoundSql boundSql = ms.getBoundSql(parameter);

    //为本次查询创建缓存的Key

    CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);

    return query(ms, parameter, rowBounds, resultHandler, key, boundSql);

 }

//进入query的重载方法中

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++;

      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();

      }

      // issue #601

      deferredLoads.clear();

      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {

        // issue #482

        clearLocalCache();

      }

    }

    return list;

  }

//从数据库查询

private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {

    List<E> list;

    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;

  }

public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {

    Statement stmt = null;

    try {

      Configuration configuration = ms.getConfiguration();

      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);

      // 创建jdbc中的statement对象

      stmt = prepareStatement(handler, ms.getStatementLog());

      return handler.query(stmt, resultHandler);

    } finally {

      closeStatement(stmt);

    }

  }

// 创建Statement的方法

private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {

    Statement stmt;

    Connection connection = getConnection(statementLog);

    stmt = handler.prepare(connection, transaction.getTimeout());

    handler.parameterize(stmt);

    return stmt;

  }

protected void openConnection() throws SQLException {

    if (log.isDebugEnabled()) {

      log.debug("Opening JDBC Connection");

    }

    connection = dataSource.getConnection();

    if (level != null) {

      connection.setTransactionIsolation(level.getLevel());

    }

    setDesiredAutoCommit(autoCommit);

  }public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {

    PreparedStatement ps = (PreparedStatement) statement;

    //原生jdbc的执行

    ps.execute();

    //处理结果返回。

    return resultSetHandler.handleResultSets(ps);

  }

进入sqlSession.getMapper(UserMapper.class):

//DefaultSqlSession中的getMapper

public <T> T getMapper(Class<T> type) {

    return configuration.<T>getMapper(type, this);

}

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {

    return mapperRegistry.getMapper(type, sqlSession);

}

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {

    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);

    if (mapperProxyFactory == null) {

      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");

    }

    try {

      // 通过动态代理工厂生成示例。

      return mapperProxyFactory.newInstance(sqlSession);

    } catch (Exception e) {

      throw new BindingException("Error getting mapper instance. Cause: " + e, e);

    }

}

//MapperProxyFactory类中的newInstance方法

 public T newInstance(SqlSession sqlSession) {

       // 创建了JDK动态代理的Handler

    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);

    return newInstance(mapperProxy);

  }

public class MapperProxy<T> implements InvocationHandler, Serializable {

  private final SqlSession sqlSession;

  private final Class<T> mapperInterface;

  private final Map<Method, MapperMethod> methodCache;

 

  // 构造,传入了SqlSession,说明每个session中的代理对象的不同的!

  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {

    this.sqlSession = sqlSession;

    this.mapperInterface = mapperInterface;

    this.methodCache = methodCache;

  }

}

//重载的方法,由动态代理创建新示例返回。

protected T newInstance(MapperProxy<T> mapperProxy) {

    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, 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);

    }

    final MapperMethod mapperMethod = cachedMapperMethod(method);

    return mapperMethod.execute(sqlSession, args);

  }

public Object execute(SqlSession sqlSession, Object[] args) {

    Object result;

    //判断mapper中的方法类型,最终调用的还是SqlSession中的方法

    switch (command.getType()) {

      case INSERT: {

    Object param = method.convertArgsToSqlCommandParam(args);

        result = rowCountResult(sqlSession.insert(command.getName(), param));

        break;

      }

      case UPDATE: {

        Object param = method.convertArgsToSqlCommandParam(args);

        result = rowCountResult(sqlSession.update(command.getName(), param));

        break;

      }

      case DELETE: {

        Object param = method.convertArgsToSqlCommandParam(args);

        result = rowCountResult(sqlSession.delete(command.getName(), param));

        break;

      }

      case SELECT:

        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 if (method.returnsCursor()) {

          result = executeForCursor(sqlSession, args);

        } else {

          Object param = method.convertArgsToSqlCommandParam(args);

          result = sqlSession.selectOne(command.getName(), param);

          if (method.returnsOptional() &&

              (result == null || !method.getReturnType().equals(result.getClass()))) {

            result = Optional.ofNullable(result);

          }

        }

        break;

      case FLUSH:

        result = sqlSession.flushStatements();

        break;

      default:

        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;

  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值