学习笔记之Mybatis源码(一)

    使用Mybatis时,经常通过下面的代码获取SqlSession对象然后使用getMapper方法获取相应的mapper对象,通过mapper对象执行数据库的增删改查操作。

SqlSessionFactoryBuilder sqlSessionFactoryBuilder =null;
SqlSessionFactory sqlSessionFactory = null;
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
sqlSessionFactory=sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
user2Mapper.insertUser(user);
session.commit();

    可是我们只定义了Mapper接口并没有实现接口,那么Mybatis是如何帮助我们完成数据库操作的呢?
    首先是通过SqlSessionFactoryBuilder的build方法获取sqlSessionFactory ,在build方法中会通过XMLConfigBuilder解析全局xml文件并封装为Configuration对象,然后使用Configuration对象创建默认的DefaultSqlSessionFactory 。build方法代码如下:

public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
  try {
    XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
    return build(parser.parse());
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  } finally {
    ErrorContext.instance().reset();
    try {
      reader.close();
    } catch (IOException e) {
      // Intentionally ignore. Prefer previous error.
    }
  }
}

public SqlSessionFactory build(Configuration config) {
  return new DefaultSqlSessionFactory(config);
}

    然后调用SqlSessionFactory的openSession方法获取SqlSession,openSession方法返回默认的DefaultSqlSession对象。openSession方法代码如下:

@Override
public SqlSession openSession() {
  return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
  Transaction tx = null;
  try {
    final Environment environment = configuration.getEnvironment();
    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    final Executor executor = configuration.newExecutor(tx, execType);//Excutor执行器,真正执行数据库操作的组件,默认是SimpleExcutor,开启缓存的情况下使用CachingExecutor(Mybatis默认开启缓存)
    return new DefaultSqlSession(configuration, executor, autoCommit);//DefaultSqlSession实现了SqlSession接口
  } 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();
  }
}

    获取到DefaultSqlSession对象后我们调用了getMapper方法,通过源码可以看DefaultSqlSession的getMapper方法中调用了Configuration的getMapper方法。DefaultSqlSession的getMapper方法代码如下:

@Override
public <T> T getMapper(Class<T> type) {
  return configuration.<T>getMapper(type, this);
}

    继续跟下去发现MapperRegistry的getMapper方法调用了MapperProxyFactory的newInstance方法,看名称可以知道在这里创建了Mapper接口的代理对象。MapperRegistry的getMapper方法代码如下:

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

    进入newInstance方法中看看,可以看到Mybatis使用JDK动态代理为Mapper接口生产代理对象。newInstance方法代码如下:

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

    既然是动态代理,那我们就去就看看代理类MapperProxy重写的invoke方法,这段代码的大意是:如果调用由Object继承而来的方法(如toString)就直接使用反射调用,否则使用MapperMehtod的execute方法。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);
}

    查看execute源码,发现调用了SqlSession的是增删改查方法。execute方法代码如下:

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.getName() 
        + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
  }
  return result;
}

    查看DefaultSqlSession的selectOne方法,发现最终调用了selectList,并在selectList方法中调用了executor的query方法去查询。selectList方法代码如下:

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

总结
1.SqlSessionFactoryBuilder使用XMLConfigBuilder解析全局xml文件并保存在Configuration对象中,使用Configuration对象初始化DefaultSqlSessionFactory。

2.SqlSessionFactory主要负责创建默认的DefaultSqlSession(Excutor也在这里创建)。

3.使用getMapper方法时,使用JDK动态代理为Mapper接口创建代理对象。

4.具体完成数据库操作的组件是SqlSession中的Excutor。

发布了4 篇原创文章 · 获赞 0 · 访问量 40

猜你喜欢

转载自blog.csdn.net/weixin_44247853/article/details/105175735