简述

  • 在我们使用Mybatis进行增删改查时,SqlSession是核心,它相当于一个数据库连接对象,在一个SqlSession中可以执行多条SQL语句
  • SqlSession本身是一个接口,提供了很多种操作方法,如insert,select等等,我们可以直接调用,但是这种方式是不推荐的,可读性,可维护性都不是很高,推荐使用Mapper接口映射的方式去进行增删改查,了解一下这种方式的运行过程也是有必要的
  • 在了解SqlSession运行过程前,我们需要具备动态代理以及JDK动态代理的相关知识

开始分析

我们在使用Mapper时,基本流程就是在配置文件中指定好Mapper接口文件和XML文件的路径,然后使用如下代码获取代理对象

UserMapper userMapper = sqlSession.getMapper(UserMapper.class)

然后调用接口中的方法即可调执行相关的SQL语句,这一过程是具体怎么执行的呢?下面开始分析

【getMapper方法】
  • SqlSession只是一个接口,Mybatis中使用的是它的默认实现类DefaultSqlSession
@Override
  public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }
  • 调用Configuration的getMapper方法
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
  • 继续调用MapperRegistry的getMapper方法
@SuppressWarnings("unchecked")
  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);
    }
  }

这里需要介绍一下,我们在写XML配置文件时注册了Mapper,被注册的Mapper就被维护在MapperRegistry的一个HashMap中

private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();

map的key是Class类,value是对应的一个代理工厂MapperProxyFactory,用来生产对应的代理类,如果key没有对应的value,会抛出异常,告诉我们并没有去注册这个Mapper,这时候就需要去检查配置文件了

  • 调用MapperProxyFactory的newInstance()方法去生产代理对象
public T newInstance(SqlSession sqlSession) {
    //生产代理,该对象必须实现InvocationHandler接口且实现invoke方法
    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);
  }

这里就涉及到了JDK动态代理

  1. 首先new一个Mapper代理,由JDK动态代理可知,代理对象必须实现InvocationHandler接口且实现invoke方法
  2. 调用Proxy.newProxyInstance方法产生代理对象

为什么要动态代理呢?因为我们要执行SQL!在接口方法中,我们是不需要自己写查询方法的,而SQL方法的执行就依赖于动态代理!

  • 动态代理的主要逻辑就是invoke方法中的内容,我们来看MapperProxy的invoke方法
@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);
  }

简单描述一些流程

  1. 我们知道Java中,所有类的父类都是Object,因此所有类都会继承一些Object的方法,如toString()之类的,所以这里我们要进行判断,如果我们的代理对象调用的是从Object那里继承来的方法,我们就不去执行动态代理逻辑,而是直接执行该方法
  2. 如果执行的方法归本类所有,则通过cachedMapperMethod产生MapperMethod来执行execute代理逻辑,即执行SQL
【这里涉及到了一个很重要的问题!!!】

我们知道,XML映射文件其实就是Mapper接口的实现类,接口方法的全路径和XML映射文件中namesapce + SQL块的id一一对应,Mybatis是如何找到并维护这种对应关系的呢?就是通过MapperProxy中的一个Map

private final Map<Method, MapperMethod> methodCache;

这个Map的key为传入的方法类型,value为MapperMethod,也是执行SQL的关键,其实这个methodCache主要是为了完成缓存的任务,因为我们执行方法时,需要从Configuration中去解析对应的XML文件中的SQL块,多次解析会造成资源的浪费,代码如下

private MapperMethod cachedMapperMethod(Method method) {
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

若key对应的value存在,则从map直接拿到并返回,若不存在,则通过

mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());

解析后,放入map,并返回,下面看是如何解析的

private final SqlCommand command;
  private final MethodSignature method;

  public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    this.method = new MethodSignature(config, mapperInterface, method);
  }

在MapperMethod中有两个成员变量command和method,command主要完成了根据method方法解析出对应的SQL块,而method负责一些如传参的转化,返回类型的判定等,这里我们主要看command解析(注释中)

public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
      //1、拿到接口全路径.方法名称的字符串,这不就是XML映射文件中的namespace.id吗?
      String statementName = mapperInterface.getName() + "." + method.getName();
      MappedStatement ms = null;
      if (configuration.hasStatement(statementName)) {
        //2、判断Configuration中是否含有该配置,有则拿到MappedStatement
        ms = configuration.getMappedStatement(statementName);
      } else if (!mapperInterface.equals(method.getDeclaringClass())) { // issue #35
        //3、如果不存在,看看它的父类全路径.方法名称是否存在
        String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName();
        if (configuration.hasStatement(parentStatementName)) {
          ms = configuration.getMappedStatement(parentStatementName);
        }
      }
      if (ms == null) {
        //如果MappedStatement为空
        if(method.getAnnotation(Flush.class) != null){
          //先瞅瞅执行的这个方法有木有@Flush注解呢?有就执行下面操作
          name = null;
          type = SqlCommandType.FLUSH;
        } else {
          //没有。。。那就抛异常呗,赶紧去检查是不是XML和接口对应写错了?
          throw new BindingException("Invalid bound statement (not found): " + statementName);
        }
      } else {
        //不等于空就执行下面操作
        name = ms.getId();
        type = ms.getSqlCommandType();
        if (type == SqlCommandType.UNKNOWN) {
          throw new BindingException("Unknown execution method for: " + name);
        }
      }
    }

至此根据method解析SQL块完毕,这一系列初始化过程在new这个MapperMethod对象后便完成了,然后便调用execute方法进行执行代理方法,即SQL执行!

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));
    } else if (SqlCommandType.UPDATE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.update(command.getName(), param));
    } else if (SqlCommandType.DELETE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.delete(command.getName(), param));
    } else if (SqlCommandType.SELECT == command.getType()) {
      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);
      }
    } else if (SqlCommandType.FLUSH == command.getType()) {
        result = sqlSession.flushStatements();
    } else {
      throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.ge
tName() 
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }

这一段代码就不去一一解析了,主要就是通过初始化好的command,拿到SQL块的id以及类型,method拿到SQL参数以及返回类型,通过调用sqlSession的原生方法如select、selectOne、insert、update等等去执行SQL