mybatis之bind模块

Posted 我爱看明朝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis之bind模块相关的知识,希望对你有一定的参考价值。

mybatis之bind模块

mybatis通过定义接口mapper,不需要继承或实现接口,Mapper接口中的方法定义select|update|insert|delete方法,通过关联映射文件中定义的sql来执行查询。

 .....org.apache.ibats
 ....................binding
 ...........................BindingException
 ...........................MapperMethod
 ...........................MapperProxy
 ...........................MapperProxyFactory
 ...........................MapperRegistry

执行流程

MybatisUse
DefaultSqlSession
Configuration
MapperRegistry
MapperProxyFactory
MapperProxy
MapperMethod
public class MybatisUse {

    public static void main(String[] args) throws Exception{
        //加载mybatis的配置文件
        String mybatisXml = "mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(mybatisXml);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取sqlSession的实现DefaultSqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过MapperRegistry获取到Mapper的代理
        CleanPolicyMapper cleanPolicyMapper = sqlSession.getMapper(CleanPolicyMapper.class);
        // 通过MapperMethod执行查询、更新、插入、删除方法逻辑
        CleanPolicy cleanPolicy = cleanPolicyMapper.selectById(292L);
        System.out.println("name:" + cleanPolicy.getName());

        sqlSession.commit();
        sqlSession.flushStatements();
        sqlSession.close();

    }
}

来大体看看调用过程

CleanPolicyMapper cleanPolicyMapper = sqlSession.getMapper(CleanPolicyMapper.class);
//DefaultSqlSession
public class DefaultSqlSession implements SqlSession {
    @Override
    public <T> T getMapper(Class<T> type) {
        return configuration.<T>getMapper(type, this);
    }
}

public class Configuration {
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        return mapperRegistry.getMapper(type, sqlSession);
    }
}
public class MapperRegistry {
    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);
        }
    }
}
//调用接口对应的方法
CleanPolicy cleanPolicy = cleanPolicyMapper.selectById(292L);
//CleanPolicy ---> 对应这里的MapperProxy对象
public class MapperProxy<T> implements InvocationHanlder, Serializable {

 //代理调用方法
  @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);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //调用执行方法
    return mapperMethod.execute(sqlSession, args);
  }
}

public class MapperMethod {

    //根据执行选择对应的方法
    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;
  }


}

    classDiagram
        MapperRegistry *-- MapperProxyFactory
        MapperProxyFactory <.. MapperProxy
        MapperProxy *-- MapperMethod
        MapperProxyFactory *-- MapperMethod

MapperRegistry

MapperRegistry映射注册器核心两个方法getMapper和addMapper

public class MapperRegistry {
    private final Configuration config;
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();

    // 查询mapper接口的代理对象
    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 (

以上是关于mybatis之bind模块的主要内容,如果未能解决你的问题,请参考以下文章

带你彻底搞懂MyBatis的底层实现之binding模块

带你彻底搞懂MyBatis的底层实现之binding模块

浩哥解析MyBatis源码——binding绑定模块之MapperRegisty

带你彻底搞懂MyBatis的底层实现之缓存模块(Cache)-吊打面试官必备技能

带你彻底搞懂MyBatis的底层实现之缓存模块(Cache)-吊打面试官必备技能

mybatis错误之org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)