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

  • 相关阅读:
    设计模式7—装饰者模式【结构型】
    设计模式6—命令模式【行为型】
    vue工程类型—vue 多模块、vue多项目集成工程
    设计模式5—迭代器模式【行为型】
    设计模式4—代理模式【结构型】
    设计模式3—策略模式【行为型】
    用户权限管理系统(后台权限管理)
    https原理 及 证书
    设计模式2—单例模式【创建型】
    设计模式1—发布订阅者模式【行为型】
  • 原文地址:https://www.cnblogs.com/juniorMa/p/13933413.html
Copyright © 2011-2022 走看看