Mybatis 之 MapperMethod

从 Mybatis 之 构造Mapper (MapperProxy)  http://blog.csdn.net/zsg88/article/details/77921009  一文中我们已经知道

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);  

返回的其实是一个MapperProxy代理类

org.apache.ibatis.binding.MapperProxyFactory

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

那么又是怎样通过Mapper代理类调用具体方法的。我们先看MapperProxy类实现的InvocationHanlder.invoke方法:

org.apache.ibatis.binding.MapperProxy

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

判断是否是一个类,如果是一个类,那么久直接传递方法和参数调用即可。但我们知道此时是一个接口(也可以自己实现接口,旧版本通常这样做)。如果不是一个类的话,就会创建一个MapperMethod对象来执行方法。


MapperMethod类和数据库进行操作,看看execute方法:

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

我们选择常见的"SELECT"sql语句来进行解读,其中的executeForMany方法:

  private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
    List<E> result;
    Object param = method.convertArgsToSqlCommandParam(args);
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
    } else {
      result = sqlSession.<E>selectList(command.getName(), param);
    }
    // issue #510 Collections & arrays support
    if (!method.getReturnType().isAssignableFrom(result.getClass())) {
      if (method.getReturnType().isArray()) {
        return convertToArray(result);
      } else {
        return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
      }
    }
    return result;
  }

真正执行sql语句的地方

if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
    } else {
      result = sqlSession.<E>selectList(command.getName(), param);
    }

最后又回到了sqlSession的方法中。看到传递了什么参数进来,跟踪command.getName()是怎么来的。

private final SqlCommand command;

我们可以发现这个SqlCommand是MapperMethod的静态内部类。

//org.apache.ibatis.binding.MapperMethod
  public static class SqlCommand {

    private final String name;
    private final SqlCommandType type;

    public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {      
      //获取接口+方法名
String statementName = mapperInterface.getName() + "." + method.getName(); 
      //定义一个MappedStatement
MappedStatement ms = null;   if (configuration.hasStatement(statementName)) {
        //从Configuration对象查找是否有这个方法的全限定名称 
        //有,则根据方法的全限定名称获取MappedStatement实例 
ms = configuration.getMappedStatement(statementName);  
      } else if (!mapperInterface.equals(method.getDeclaringClass())) { // issue #35
        //如果没有在Configuration对象中找到这个方法,则向上父类中获取全限定方法名
String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName(); if (configuration.hasStatement(parentStatementName)) {  //在向上的父类查找是否有这个全限定方法名 ms = configuration.getMappedStatement(parentStatementName);   //有,则根据方法的全限定名称获取MappedStatement实例 } } if (ms == null) { if(method.getAnnotation(Flush.class) != null){ name = null; type = SqlCommandType.FLUSH; } else { throw new BindingException("Invalid bound statement (not found): " + statementName); } } else { name = ms.getId();  //这个ms.getId,其实就是我们在mapper.xml配置文件中配置一条sql语句时开头的<select id="xxx" ...,即是接口的该方法名全限定名称 type = ms.getSqlCommandType();  //显然这是将sql是何种类型(insert、update、delete、select)赋给type if (type == SqlCommandType.UNKNOWN) { throw new BindingException("Unknown execution method for: " + name); } } } public String getName() { return name; } public SqlCommandType getType() { return type; } }













`MapperMethod.ParamMap` 是 MyBatis 中用于封装参数的对象。在 MyBatis 中,参数可以通过不同的方式传递给 Mapper 方法,其中包括单个参数和参数映射。 对于你提到的两种情况,`ew` 通常指的是某个实体对象(Entity Wrapper),例如 `Example` 对象或其他类型的包装对象,而 `coll` 可能代表一个集合类型,比如 `List` 或 `Set`。 为了全面解析 `MapperMethod.ParamMap`,你可以采用以下策略: 1. **遍历 ParamMap**:ParamMap 本质上是一个 Map,它将参数名映射到参数值。你可以遍历这个 Map 来检查每个参数的内容和类型。 2. **区分参数类型**:在遍历过程中,对于每个参数,你需要检查它是单一类型还是集合类型。这可以通过检查参数的类类型来实现。例如,使用 `instanceof` 操作符或者 `isAssignableFrom` 方法来判断参数是否为特定集合类型。 3. **单独处理**:一旦确定了参数类型,你可以根据其类型采取不同的策略。例如,如果参数是实体对象,你可以进一步访问其属性;如果参数是集合,你可以遍历集合中的每个元素。 4. **支持多参数**:对于多参数的情况,你可能需要处理多个键值对,其中键可能是参数名或索引,值可能是单个对象或集合。 5. **考虑 @Param 注解**:在使用 `@Param` 注解时,每个参数都会有一个明确的名称。这有助于在映射参数时更准确地处理它们。 一个简单的示例代码如下: ```java public Object parseParams(Map<String, Object> paramMap) { for (Map.Entry<String, Object> entry : paramMap.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // 根据参数类型采取不同的处理方式 if (value instanceof YourEntityWrapperClass) { // 处理实体对象类型参数 } else if (value instanceof Collection) { // 处理集合类型参数 Collection<?> collection = (Collection<?>) value; for (Object item : collection) { // 处理集合中的每个元素 } } else { // 处理其他类型参数 } } // 返回解析后的参数或构建的参数对象 } ``` 在实际应用中,你可能需要根据具体的业务逻辑和参数类型来设计更复杂的解析策略。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值