02.MyBatis 源码分析之获取实现类

1. 时序图

MyBatis -getMapper 时序图

2. 通过 getMapper 获取实现类

@Test
public void test() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    // 1、获取 sqlSessionFactory 对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // 2、获取 sqlSession 对象       ------> 3
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        // 3、获取接口的实现类       ------> 4
        EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
        // 4、执行目标方法
        Employee employee = mapper.getEmpById(1);
        System.out.println(employee);
    } finally {
        openSession.close();
    }
}

3. 获取 SqlSession

3.1 DefaultSqlSessionFactory#openSession
  • org.apache.ibatis.session.defaults.DefaultSqlSessionFactory
@Override
public SqlSession openSession() {
    // configuration.getDefaultExecutorType()       ------> 3.2
    // openSessionFromDataSource(),从数据库中获取  SqlSession       ------> 3.3
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
3.2 Configuration#getDefaultExecutorType
  • org.apache.ibatis.session.Configuration
public ExecutorType getDefaultExecutorType() {
    // ExecutorType defaultExecutorType = ExecutorType.SIMPLE,即返回一个 simpleExecutorType
    return defaultExecutorType;
}
3.3 DefaultSqlSessionFactory#openSessionFromDataSource
  • org.apache.ibatis.session.defaults.DefaultSqlSessionFactory
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      // 从 configuration 中获取 environment
      final Environment environment = configuration.getEnvironment();
      // 从 environment 获取 transactionFactory
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      // 根据数据库的配置,创建一个 transaction
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      // 创建一个 executor 执行器       ------> 3.4
      final Executor executor = configuration.newExecutor(tx, execType);
      // 创建一个 DefaultSqlSession 对象,传入了 configuration、executor
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
}
3.4 Configuration#newExecutor
  • org.apache.ibatis.session.Configuration
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      // 创建一个 SimpleExecutor
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      // 如果开启了缓存,创建一个 CachingExecutor,包装 SimpleExecutor,装饰模式
      executor = new CachingExecutor(executor);
    }
    // 用插件包装 CachingExecutor       ------> 3.5
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}
3.5 InterceptorChain#pluginAll
  • org.apache.ibatis.plugin.InterceptorChain
public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      // 调用插件的 plugin 方法包装 executor 后返回
      target = interceptor.plugin(target);
    }
    return target;
}

4. 调用 getMapper 获取实现类

4.1 DefaultSqlSession#getMapper
  • org.apache.ibatis.session.defaults.DefaultSqlSession
@Override
public <T> T getMapper(Class<T> type) {
    // 调用 configuration.getMapper() 方法      ------> 4.2
    return configuration.<T>getMapper(type, this);
}
4.2 Configuration#getMapper
  • org.apache.ibatis.session.Configuration
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 调用 mapperRegistry.getMapper() 方法      ------> 4.3
    return mapperRegistry.getMapper(type, sqlSession);
}
4.3 MapperRegistry#getMapper
  • org.apache.ibatis.binding.MapperRegistry
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 获取 mapperProxyFactory
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      // 调用 mapperProxyFactory.newInstance() 方法     ------> 4.4
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
}
4.4 MapperProxyFactory#newInstance
  • org.apache.ibatis.binding.MapperProxyFactory
public T newInstance(SqlSession sqlSession) {
    // 构建 mapperProxy 对象
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    // 调用 newInstance() 方法      ------> 4.5
    return newInstance(mapperProxy);
}
4.5 MapperProxyFactory#newInstance
  • org.apache.ibatis.binding.MapperProxyFactory
protected T newInstance(MapperProxy<T> mapperProxy) {
    // 用 jdk 的动态代理生产实现类      ------> 4.6
    // 注意此处是为 mapperProxy 生成代理类,并非是为 XxxMapper 生成,这样就不需要 XxxMapper 的实现类了
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
4.6 Proxy#newProxyInstance
  • java.lang.reflect.Proxy
public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
{
    Objects.requireNonNull(h);

    final Class<?>[] intfs = interfaces.clone();
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
    }

    // 断点到此处,可调用 cl.getMethods() 查看所有方法
    Class<?> cl = getProxyClass0(loader, intfs);

    ...
    
}
  • mapperProxy 会为 getEmpById() 方法生成代理方法,所有的代理方法如下
0 = {Method@1751} "public final boolean com.sun.proxy.$Proxy4.equals(java.lang.Object)"
1 = {Method@1752} "public final java.lang.String com.sun.proxy.$Proxy4.toString()"
2 = {Method@1753} "public final int com.sun.proxy.$Proxy4.hashCode()"
3 = {Method@1754} "public final pers.mangseng.study.mybatis.pojo.Employee com.sun.proxy.$Proxy4.getEmpById(java.lang.Integer)"
4 = {Method@1755} "public static boolean java.lang.reflect.Proxy.isProxyClass(java.lang.Class)"
5 = {Method@1756} "public static java.lang.Object java.lang.reflect.Proxy.newProxyInstance(java.lang.ClassLoader,java.lang.Class[],java.lang.reflect.InvocationHandler) throws java.lang.IllegalArgumentException"
6 = {Method@1757} "public static java.lang.reflect.InvocationHandler java.lang.reflect.Proxy.getInvocationHandler(java.lang.Object) throws java.lang.IllegalArgumentException"
7 = {Method@1758} "public static java.lang.Class java.lang.reflect.Proxy.getProxyClass(java.lang.ClassLoader,java.lang.Class[]) throws java.lang.IllegalArgumentException"
8 = {Method@1759} "public final void java.lang.Object.wait() throws java.lang.InterruptedException"
9 = {Method@1760} "public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException"
10 = {Method@1761} "public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException"
11 = {Method@1762} "public final native java.lang.Class java.lang.Object.getClass()"
12 = {Method@1763} "public final native void java.lang.Object.notify()"
13 = {Method@1764} "public final native void java.lang.Object.notifyAll()"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值