mybatis的创建SqlSession的过程:

image.png

Mybatis使用代理Dao的执行过程:

Mybatis只需提供一个Dao接口,就可以实现与数据库的CRUD交互,这种情形,我们很容易想到用JDK动态代理去实现,事实上也确实如此。
客户端是通过拿到Mybatis提供的Dao接口的代理对象,来进行CRUD操作,过程如下:
image.png

源码如下,熟悉的Proxy.newProxyInstance

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

看下MapperProxy类的invoke方法也比较简单,这个方法主要作用是从缓存methodCache中获取MapperMethod,进行对应CRUD操作。

 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      // 执行Object类的方法
      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);
    }
    // 从缓存中获取MapperMethod,CRUD方法就在其中
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

SanPiBrother
24 声望3 粉丝

菜鸡的救赎之路