mybatis使用@Param的坑


在mybatis中@Param注解的作用是為參數指定一個名稱,在mapper文件中使用,而不是使用mybatis的arguments[0,1…]代替。但是在非動態的mapper——mybatis根據mapper接口創建實現類,@param注解是不起作用的。

閱讀mybatis的源碼得知,檢查@param注解的方法:

private boolean hasNamedParams(Method method) {
      boolean hasNamedParams = false;
      final Object[][] paramAnnos = method.getParameterAnnotations();
      for (Object[] paramAnno : paramAnnos) {
        for (Object aParamAnno : paramAnno) {
          if (aParamAnno instanceof Param) {
            hasNamedParams = true;
            break;
          }
        }
      }
      return hasNamedParams;
    }
View Code

此方法位於 org.apache.ibatis.binding.MapperMethod 的內部類 MethodSignature 中。根據源碼一步一步的遞歸:MethodSignature的構造方法——>MapperMethod的構造方法——>MapperProxy的cachedMapperMethod 和invoke方法 ——> MapperProxyFactory中的 newInstance 方法。

@SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
//jdk的動態代理生成mapper對象
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

  public T newInstance(SqlSession sqlSession) {
//MapperProxy實現了Invocation接口
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

 

在整合spring與mybatis,使用spring提供的sqlSessionTemplate進行查詢時,沒有從MapperRegistry的mapper緩存集合中取mapper,而是直接使用配置的sqlSessionTemplate。所以這種清況下,@param注解是無效的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM