1. 程式人生 > >mybatis原理解析---SqlSession執行過程(上)

mybatis原理解析---SqlSession執行過程(上)

sqlSession代表與資料庫的一次會話,在這次會話中可以多次執行查詢等sql操作。從前面可以看到SqlSession物件是從SqlSessionFactory物件中獲得的。sqlSession本身就定義了一系列的update select delete insert等方法,在舊版本的mybatis中是直接呼叫這些方法的,但是在mybatis3中先通過getMapper()獲取到mapper物件(一個代理物件),然後通過mapper來呼叫相應的sql。如下面所示:

//通過SqlSession物件獲取BranchMapper介面的代理物件,並通過代理物件執行sql獲取結果
BranchMapper branchMapper=sqlSession.getMapper
(BranchMapper.class); branchMapper.getBranchByNameAndCity("test","bj");

正如上面註釋所示,本質上是通過sqlSession的getMapper()方法拿到了介面的代理物件,然後通過這個代理物件去執行的相應的sql。下面從原始碼來看下代理物件的構建過程。

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

可以看到生成代理物件呼叫的是Proxy.newProxyInstance()方法,而真正的代理物件是MapperProxy類。下面來看下MapperProxy類的原始碼,下面是部分原始碼:

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 {
     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);
     }
     //cachedMapperMethod為method生成MapperMethod物件,並且還會將生成的物件快取到methodCache中,這樣下次再呼叫同樣的
     //方法就不需要重新生成了
     final MapperMethod mapperMethod = cachedMapperMethod(method);
     return mapperMethod.execute(sqlSession, args);
   }
}

首先來看下里面的幾個屬性:
sqlSession: 本次執行的資料庫會話,即sqlSession.getMapper(BranchMapper.class)中的sqlSession。
mapperInterface: sqlSession.getMapper(BranchMapper.class)傳入的BranchMapper.class,即需要被代理的Class物件。
methodCache:是一個Map物件:Map<Method, MapperMethod>,key是BranchMapper介面中的method,value是一個代理方法MapperMethod物件,為介面中的每個方法都快取了一個代理方法物件。
通過MapperMethod類的原始碼可以看到其有兩個屬性:
private final SqlCommand command;
private final MethodSignature method;
MethodSignature裡面儲存的是傳入方法的一些資訊像返回值 傳入引數等資訊。SqlCommand的原始碼如下:

public static class SqlCommand {

    private final String name;
    private final SqlCommandType type;

    public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
      final String methodName = method.getName();
      final Class<?> declaringClass = method.getDeclaringClass();
      //通過mapperInterface的全限定類名和傳入的方法名組合成的key,可以從configuration中獲取到對應的MappedStatement
      MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
          configuration);
      if (ms == null) {
        if (method.getAnnotation(Flush.class) != null) {
          name = null;
          type = SqlCommandType.FLUSH;
        } else {
          throw new BindingException("Invalid bound statement (not found): "
              + mapperInterface.getName() + "." + methodName);
        }
      } else {
        name = ms.getId();
        type = ms.getSqlCommandType();
        if (type == SqlCommandType.UNKNOWN) {
          throw new BindingException("Unknown execution method for: " + name);
        }
      }
    }

可以看到裡面最重要的邏輯就是獲取到當前介面方法對應的MappedStatement物件,然後將這個物件的id作為SqlCommand的名稱;這樣設定之後,就可以通過Method對應MappedMethod中的SqlCommand物件的name屬性獲取到關聯的MappedStatement物件。methodCache不是在初始化的時候進行填充的,而是在真正呼叫介面的方法時在invoke()方法裡進行初始化的,MappedMethod中的MethodSignature物件(描述方法的入參 返回值 解析方法引數名(包括@Param註解的引數名都是這個物件實現的))也是在invoke()方法裡實現的。
通過sqlSession.getMapper()方法拿到的是mapper是個代理物件,執行代理物件的相關方法的時候,比如執行branchMapper.getBranchByNameAndCity(“test”,”bj”);會先呼叫代理類的invoke()方法。在上面的MapperProxy的invoke()方法中,先判斷傳入的method是不是屬於一個類或者是不是預設的方法,如果不是,那麼就為當前的method生成一個MappedMethod物件,然後執行其execute()方法,將當前的sqlSession和方法引數傳入。下面來看下execute()內部的邏輯:

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

可以看到在這個方法裡面會根據傳入的查詢型別和返回結果的不同,分別呼叫不同的方法來執行sql(使用了命令模式)。但這些方法裡都是呼叫了sqlSession相應的方法進行的查詢,比如說最常用的返回多個值的查詢:

//返回多個結果的查詢
else if (method.returnsMany()) {
          result = executeForMany(sqlSession, args);

下面是executeForMany()方法的原始碼,可以看到裡面其實就是呼叫了sqlSession的selectList()方法完成的查詢:

private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
    List<E> result;
    Object param = method.convertArgsToSqlCommandParam(args);
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
    } else {
      result = sqlSession.<E>selectList(command.getName(), param);
    }
    if (!method.getReturnType().isAssignableFrom(result.getClass())) {
      if (method.getReturnType().isArray()) {
        return convertToArray(result);
      } else {
        return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
      }
    }
    return result;
  }

然後再看下sqlSession.<E>selectList(command.getName(), param)的內部實現,它裡面呼叫的是下面這個方法:

@Override
  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      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();
    }
  }

傳入的引數statement是MapperMethod中SqlCommand物件的name即Mapper介面方法對應的MappedStatement的id,parameter是MappedMethod中通過組合傳入的Method中引數名稱(@Param註解的引數名等)資訊 引數值資訊等得到的引數物件。這個方法裡會通過Configuration通過id拿到MappedStatement物件,然後通過與sqlSession關聯的executor.query()方法來執行查詢。
這裡有通過wrapCollection對傳入的parameter物件再進行一次處理,下面是具體的處理過程:

private Object wrapCollection(final Object object) {
    if (object instanceof Collection) {
      StrictMap<Object> map = new StrictMap<Object>();
      map.put("collection", object);
      if (object instanceof List) {
        map.put("list", object);
      }
      return map;
    } else if (object != null && object.getClass().isArray()) {
      StrictMap<Object> map = new StrictMap<Object>();
      map.put("array", object);
      return map;
    }
    return object;
  }

主要針對方法的引數型別是Collection List Array這三種情況並且沒有使用@Param註解的時候,提供預設的名稱值;這樣設定之後,可以在mapper.xml中直接通過#{list} #{collection} #{array}等方式進行直接引用。

現在來簡單總結下,前面的一系列過程完成了傳入引數的轉換:將入引數組args[]結合method物件中關於引數的資訊得到了parameter物件,通過傳入method物件的全限定類名加方法名取得了關聯的MappedStatement物件(完成了介面方法和mapper.xml配置sql的管理)。完成了以上兩步之後就完成了sql執行前的準備工作,接下來就是通過SqlSession中executor來執行sql獲取並轉化查詢結果了。