溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在mybatis中實現省略@Param注解

發(fā)布時間:2020-11-30 16:36:15 來源:億速云 閱讀:362 作者:Leah 欄目:開發(fā)技術

如何在mybatis中實現省略@Param注解?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

1.在mybatis的配置里有個屬性useActualParamName,允許使用方法簽名中的名稱作為語句參數名稱

我用的mybatis:3.4.2版本Configuration中useActualParamName的默認值為true

源碼簡單分析:

MapperMethod的execute方法中獲取參數的方法convertArgsToSqlCommandParam
public Object execute(SqlSession sqlSession, Object[] args) {
  Object result;
  Object param;
  switch(this.command.getType()) {
  case INSERT:
    param = this.method.convertArgsToSqlCommandParam(args);
    result = this.rowCountResult(sqlSession.insert(this.command.getName(), param));
    break;
  case UPDATE:
    param = this.method.convertArgsToSqlCommandParam(args);
    result = this.rowCountResult(sqlSession.update(this.command.getName(), param));
    break;
  case DELETE:
    param = this.method.convertArgsToSqlCommandParam(args);
    result = this.rowCountResult(sqlSession.delete(this.command.getName(), param));
    break;
  case SELECT:
    if (this.method.returnsVoid() && this.method.hasResultHandler()) {
      this.executeWithResultHandler(sqlSession, args);
      result = null;
    } else if (this.method.returnsMany()) {
      result = this.executeForMany(sqlSession, args);
    } else if (this.method.returnsMap()) {
      result = this.executeForMap(sqlSession, args);
    } else if (this.method.returnsCursor()) {
      result = this.executeForCursor(sqlSession, args);
    } else {
      param = this.method.convertArgsToSqlCommandParam(args);
      result = sqlSession.selectOne(this.command.getName(), param);
      if (this.method.returnsOptional() && (result == null || !this.method.getReturnType().equals(result.getClass()))) {
        result = Optional.ofNullable(result);
      }
    }
    break;
  case FLUSH:
    result = sqlSession.flushStatements();
    break;
  default:
    throw new BindingException("Unknown execution method for: " + this.command.getName());
  }

  if (result == null && this.method.getReturnType().isPrimitive() && !this.method.returnsVoid()) {
    throw new BindingException("Mapper method '" + this.command.getName() + " attempted to return null from a method with a primitive return type (" + this.method.getReturnType() + ").");
  } else {
    return result;
  }
}

然后再看參數是怎么來的,convertArgsToSqlCommandParam在MapperMethod的內部類MethodSignature中:

public Object convertArgsToSqlCommandParam(Object[] args) {
  return this.paramNameResolver.getNamedParams(args);
}

getNamedParams在ParamNameResolver,看一下ParamNameResolver的構造方法:

public ParamNameResolver(Configuration config, Method method) {
  Class<?>[] paramTypes = method.getParameterTypes();
  Annotation[][] paramAnnotations = method.getParameterAnnotations();
  SortedMap<Integer, String> map = new TreeMap();
  int paramCount = paramAnnotations.length;

  for(int paramIndex = 0; paramIndex < paramCount; ++paramIndex) {
    if (!isSpecialParameter(paramTypes[paramIndex])) {
      String name = null;
      Annotation[] var9 = paramAnnotations[paramIndex];
      int var10 = var9.length;

      for(int var11 = 0; var11 < var10; ++var11) {
        Annotation annotation = var9[var11];
        if (annotation instanceof Param) {
          this.hasParamAnnotation = true;
          name = ((Param)annotation).value();
          break;
        }
      }

      if (name == null) {
        if (config.isUseActualParamName()) {
          name = this.getActualParamName(method, paramIndex);
        }

        if (name == null) {
          name = String.valueOf(map.size());
        }
      }

      map.put(paramIndex, name);
    }
  }

  this.names = Collections.unmodifiableSortedMap(map);
}

isUseActualParamName出現了,總算找到正主了,前邊一堆都是瞎扯。

2.只有這一個屬性還不行,還要能取到方法里定義的參數名,這就需要java8的一個新特性了,在maven-compiler-plugin編譯器的配置項中配置-parameters參數。

在Java 8中這個特性是默認關閉的,因此如果不帶-parameters參數編譯上述代碼并運行,獲取到的參數名是arg0,arg1......

帶上這個參數后獲取到的參數名就是定義的參數名了,例如void test(String testArg1, String testArg2),取到的就是testArg1,testArg2。

最后就把@Param注解給省略了,對于想省事的開發(fā)來說還是挺好用的

補充知識:mybatis使用@param("xxx")注解傳參和不使用的區(qū)別

我就廢話不多說了,大家還是直接看代碼吧~

public interface SystemParameterMapper {
  int deleteByPrimaryKey(Integer id);

  int insert(SystemParameterDO record);

  SystemParameterDO selectByPrimaryKey(Integer id);//不使用注解

  List<SystemParameterDO> selectAll();

  int updateByPrimaryKey(SystemParameterDO record);

  SystemParameterDO getByParamID(@Param("paramID") String paramID);//使用注解
}

跟映射的xml

<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
  select id, paramID, paramContent, paramType, memo
  from wh_system_parameter
  where id = #{id,jdbcType=INTEGER}
 </select>

<select id="getByParamID" resultMap="BaseResultMap">
  select id, paramID, paramContent, paramType, memo
  from wh_system_parameter
  where paramID = #{paramID}
 </select>

關于如何在mybatis中實現省略@Param注解問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI