Mybatis的执行经过简述

注:CSDN的博客在审核中 图片和排版可以等审核过了去http://blog.csdn.net/zyb2017/article/details/78080386查看

最近看了一些Mybatis的执行,很多不是很懂,将看到的大概写给自己零散的记录一下,一些具体分析放在以后整理整合。

# 执行流程图
网上有很多的执行流程图,个人认为比较明确的是这个:

![Mybatis执行流程图](https://img-blog.csdn.net/20170924212649552?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvenliMjAxNw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

觉得大概可以分为四部分:

 1. 参数语句的传入
 2. Myabtis中读取配置文件,执行器的选择,Statement的调用
 3. 对数据库进行访问
 4. 将输出对象返回

本文对第二步进行简单概述

# 如何生成执行语句的statement?

1.首先Mybatis要通过默认的sql会话获取Mapper,通过调用configuration的getMapper方法

```
 @Override
  public  T getMapper(Class type) {
    return configuration.getMapper(type, this);
  }
```
2.configuration调用mapperRegistry.getMapper

```
 public  T getMapper(Class type, SqlSession sqlSession) {
   return mapperRegistry.getMapper(type, sqlSession);
 }
```
3.MapperRegistry获取Mapper

```
 @SuppressWarnings("unchecked")
  public  T getMapper(Class type, SqlSession sqlSession) {
    final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) 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);
    }
  }
```
mapper代理工厂将sql会话传入,new一个新的实例,那代理工厂是如何去new的呢?

4.MapperProxyFactory的执行

通过反射新建了代理工厂,用来动态的代理dao
这里不是很懂,源码中用了@SuppressWarnings注解来抑制编译器的警告信息
```
 @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

```

```
 public T newInstance(SqlSession sqlSession) {
    final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }
```
5.Mapper代理的执行

```
public class MapperProxy implements InvocationHandler, Serializable {
  private static final long serialVersionUID = -6424540398559729838L;
  private final SqlSession sqlSession;
  private final Class mapperInterface;
  private final Map methodCache;
  public MapperProxy(SqlSession sqlSession, Class mapperInterface, Map methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }
  @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);
  }
  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;
  }
}
```
抛去其他,可以看到其实是mapperMethod在执行,调用execute

6.来到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;
  }
```

根据选择的不同去执行sqlsession中的不同方法,然后调用executor去具体处理


再此处记录一下:executor接口 ,Statement封装 ,sql的具体执行过程

转载于:https://my.oschina.net/u/3545445/blog/1542600

你可能感兴趣的:(java,数据库)