zoukankan      html  css  js  c++  java
  • Mybatis是怎么执行一条语句的

      根据官方的推荐方式,通过mapper的方式执行sql,mapper的方式就是动态代理

      所以,我们就先看动态代理的入口

      一 MapperMethod

    public class MapperProxy<T> implements InvocationHandler, Serializable {
    
      private static final long serialVersionUID = -6424540398559729838L;
      private final SqlSession sqlSession;
      private final Class<T> mapperInterface;
      private final Map<Method, MapperMethod> methodCache;
    
      public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
      }
    
      @Override
      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
          try {
            return method.invoke(this, args);
          } catch (Throwable t) {
            throw ExceptionUtil.unwrapThrowable(t);
          }
        }
        final MapperMethod mapperMethod = cachedMapperMethod(method);
        return mapperMethod.execute(sqlSession, args);
      }

      结论就是 从 MapperMethod开始执行

      二 SqlSession 

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

      三 Executor 

    @Override
      public int update(String statement, Object parameter) {
        try {
          dirty = true;
          MappedStatement ms = configuration.getMappedStatement(statement);
          return executor.update(ms, wrapCollection(parameter));
        } catch (Exception e) {
          throw ExceptionFactory.wrapException("Error updating database.  Cause: " + e, e);
        } finally {
          ErrorContext.instance().reset();
        }
      }

      四 StatementHandler

    @Override
      public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
        Configuration configuration = ms.getConfiguration();
        StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
        Statement stmt = prepareStatement(handler, ms.getStatementLog());
        return handler.update(stmt);
      }

      总结就是,mybatis的执行链路,

      1 MapperMethod

      2 SqlSession 

      3 Executor 

      4 StatementHandler

  • 相关阅读:
    OC中Foundation框架之NSDictionary、NSMutableDictionary
    【03_136】Single Number
    【算法】QuickSort
    【02_258】Add Digits
    【01_292】Nim Game
    做题过程中得到的注意点
    No.02——第一次使用Android Studio,并创建出Hello World
    No.01——配置编程环境
    一个好用的代码分享网站
    【数据结构】某些难理解点
  • 原文地址:https://www.cnblogs.com/juniorMa/p/13933413.html
Copyright © 2011-2022 走看看