做为一个程序员,你必须知道的 MyBatis解析和运行原理!

构建SqlSessionFactory过程

构建主要分为2步:java

  • 经过XMLConfigBuilder解析配置的XML文件,读出配置参数,包括基础配置XML文件和映射器XML文件;
  • 使用Configuration对象建立SqlSessionFactory,SqlSessionFactory是一个接口,提供了一个默认的实现类DefaultSqlSessionFactory。

说白了,就是将咱们的全部配置解析为Configuration对象,在整个生命周期内,能够经过该对象获取须要的配置。mysql

因为插件须要频繁访问映射器的内部组成,会重点这部分,了解这块配置抽象出来的对象:web

开始以前,记得点赞收藏加关注哦 ,须要下载PDF版本和更多知识点、面试题的朋友能够点一点下方连接免费领取面试

连接:点这里!!! 799215493 暗号:CSDNsql

在这里插入图片描述

MappedStatement

它保存映射器的一个节点(select|insert|delete|update),包括配置的SQL,SQL的id、缓存信息、resultMap、parameterType、resultType等重要配置内容。数据库

它涉及的对象比较多,通常不去修改它。缓存

SqlSource

它是MappedStatement的一个属性,主要做用是根据参数和其余规则组装SQL,也是很复杂的,通常也不用修改它。app

BoundSql

对于参数和SQL,主要反映在BoundSql类对象上,在插件中,经过它获取到当前运行的SQL和参数以及参数规则,做出适当的修改,知足特殊的要求。jvm

BoundSql提供3个主要的属性:parameterObject、parameterMappings和sql,下面分别来介绍。ide

parameterObject为参数自己,能够传递简单对象、POJO、Map或@Param注解的参数:

  • 传递简单对象(int、float、String等),会把参数转换为对应的类,好比int会转换为Integer;
  • 若是传递的是POJO或Map,paramterObject就是传入的POJO或Map不变;
  • 若是传递多个参数,没有@Param注解,parameterObject就是一个Map<String,Object>对象,相似这样的形式{“1”:p1 , “2”:p2 , “3”:p3 … “param1”:p1 , “param2”:p2 , “param3”,p3 …},因此在编写的时候可使用#{param1}或#{1}去引用第一个参数;
  • 若是传递多个参数,有@Param注解,与没有注解的相似,只是将序号的key替换为@Param指定的name;

parameterMappings,它是一个List,元素是ParameterMapping对象,这个对象会描绘sql中的参数引用,包括名称、表达式、javaType、jdbcType、typeHandler等信息。

sql,是写在映射器里面的一条sql。

有了Configuration对象,构建SqlSessionFactory就简单了:

sqlSessionFactory = new SqlSessionFactoryBuilder().bulid(inputStream);

SqlSession运行过程

映射器的动态代理

Mapper映射是经过动态代理来实现的,使用JDK动态代理返回一个代理对象,供调用者访问。

首先看看实现InvocationHandler接口的类,它是执行本代理方法的关键,能够看到,Mapper是一个接口,会生成MapperMethod对象,调用execute方法。

public class MapperProxy<T> implements InvocationHandler, Serializable { 
 
  
  
  .....
  
  @Override
  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);
  }
}

看下面的代码,MapperMethod采用命令模式,根据不一样的sql操做,作不一样的处理。

public class MapperMethod { 
 
  
  public Object execute(SqlSession sqlSession, Object[] args) { 
 
  
    Object result;
    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;
        
        ......
        
      }
    }
  }

最后看下,生成代理类的方法,就是使用JDK动态代理Proxy来建立的。

public class MapperProxyFactory<T> { 
 
  

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

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) { 
 
  
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { 
 
   mapperInterface }, mapperProxy);
  }

}

总结下映射器的调用过程,返回的Mapper对象是代理对象,当调用它的某个方法时,实际上是调用MapperProxy#invoke方法,而映射器的XML文件的命名空间对应的就是这个接口的全路径,会根据全路径和方法名,便可以绑定起来,定位到sql,最后会使用SqlSession接口的方法使它可以执行查询。

SqlSession下的四大对象

经过上面的分析,映射器就是一个动态代理对象,进入到了MapperMethod的execute方法,它通过简单的判断就进入了SqlSession的删除、更新、插入、选择等方法,这些方法如何执行是下面要介绍的内容。

Mapper执行的过程是经过Executor、StatementHandler、ParameterHandler和ResultHandler来完成数据库操做和结果返回的,理解他们是编写插件的关键:

  • Executor:执行器,由它统一调度其余三个对象来执行对应的SQL;
  • StatementHandler:使用数据库的Statement执行操做;
  • ParameterHandler:用于SQL对参数的处理;
  • ResultHandler:进行最后数据集的封装返回处理;

在MyBatis中存在三种执行器:

  • SIMPLE:简易执行器,默认的执行器;
  • REUSE:执行重用预处理语句;
  • BATCH:执行重用语句和批量更新,针对批量专用的执行器;

以SimpleExecutor为例,说明执行过程

public class SimpleExecutor extends BaseExecutor { 
 
  

  /** * 执行查询操做 */
  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(this, ms, parameter, rowBounds, resultHandler, boundSql);
      stmt = prepareStatement(handler, ms.getStatementLog());
      return handler.<E>query(stmt, resultHandler);
    } finally { 
 
  
      closeStatement(stmt);
    }
  }
  
  /** * 初始化StatementHandler */
  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException { 
 
  
    Statement stmt;
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection);
    handler.parameterize(stmt);
    return stmt;
  }
  
  /** * 执行查询 */
  @Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException { 
 
  
    String sql = boundSql.getSql();
    statement.execute(sql);
    return resultSetHandler.<E>handleResultSets(statement);
  }
}

能够看到最后会委托给StatementHandler会话器进行处理,它是一个接口,实际建立的是RoutingStatementHandler对象,但它不是真实的服务对象,它是经过适配器模式找到对应的StatementHandler执行的。在MyBatis中,StatementHandler和Executor同样分为三种:SimpleStatementHandler、PreparedStatementHandler、CallableStatementHandler。

Executor会先调用StatementHandler的prepare方法预编译SQL语句,同时设置一些基本运行的参数。而后调用parameterize()方法启用ParameterHandler设置参数,完成预编译,跟着执行查询,用ResultHandler封装结果返回给调用者。

最后

在这里为你们整理了各个知识点模块整理文档(微服务、数据库、mysql、jvm、Redis等都有)和更多大厂面试真题,有须要的朋友能够点一点下方连接免费领取

连接点这里!!! 799215493 暗号:CSDN
在这里插入图片描述在这里插入图片描述