当前位置: 首页 > 编程笔记 >

mybatis省略@Param注解操作

欧阳炜
2023-03-14
本文向大家介绍mybatis省略@Param注解操作,包括了mybatis省略@Param注解操作的使用技巧和注意事项,需要的朋友参考一下

项目是Springboot+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注解给省略了,对于想省事的开发来说还是挺好用的

补充知识:mybatis使用@param("xxx")注解传参和不使用的区别

我就废话不多说了,大家还是直接看代码吧~

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>

区别是:使用注解可以不用加parameterType

以上这篇mybatis省略@Param注解操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持小牛知识库。

 类似资料:
  • 主要内容:1. SQL 语句映射,2. 结果集映射,3. 关系映射为了简化 XML 的配置,MyBatis 提供了注解。我们可以通过 MyBatis 的 jar 包查看注解,如下图所示。 以上注解主要分为三大类,即 SQL 语句映射、结果集映射和关系映射。下面分别进行讲解。 1. SQL 语句映射 1)@Insert:实现新增功能 2)@Select:实现查询功能 3)@SelectKey:插入后,获取id的值 以 MySQL 为例,MySQL 在插入一条数据后

  • 本文向大家介绍mybatis多个接口参数的注解使用方式(@Param),包括了mybatis多个接口参数的注解使用方式(@Param)的使用技巧和注意事项,需要的朋友参考一下 1 简介 1.1 单参数 在 Mybatis 中, 很多时候, 我们传入接口的参数只有一个。 对应接口参数的类型有两种, 一种是基本的参数类型, 一种是 JavaBean 。 例如在根据主键获取对象时, 我们只需要传入一个主

  • 省略 不推荐省略 0 值单位,原因如下: CSS 规范中可以省略单位只有 [<length-percentage>](https://drafts.csswg.org/css-values-3/#typedef-length-percentage),其他比如角度单位 deg 在 Chrome 中可以省略, 这是浏览器的 Bug。 注:可以省略的单位包括:%|em|ex|ch|rem|vw|vh|v

  • 本文向大家介绍小议Java中@param注解与@see注解的作用,包括了小议Java中@param注解与@see注解的作用的使用技巧和注意事项,需要的朋友参考一下 @ param @ param标签可以归档方法或构造器的某个单一参数,或者归档类、接口以及泛型方法的类型参数。在使用@ param标签时,我们应该针对方法的每一个参数都使用一个该标签。每个段落的第一个词会被当作参数名,而余下的部分则会被

  • 本文向大家介绍详解spring+springmvc+mybatis整合注解,包括了详解spring+springmvc+mybatis整合注解的使用技巧和注意事项,需要的朋友参考一下 每天记录一点点,慢慢的成长,今天我们学习了ssm,这是我自己总结的笔记,大神勿喷!谢谢,主要代码!! ! spring&springmvc&mybatis整合(注解) 1.jar包 2.引入web.xml文件 3.创

  • 本文向大家介绍C++ 参数省略,包括了C++ 参数省略的使用技巧和注意事项,需要的朋友参考一下 示例 当将参数传递给函数时,参数是函数参数类型的prvalue表达式,而该类型不是引用,则可以忽略prvalue的构造。 这表示要创建一个临时文件string,然后将其移动到function参数中str。复制省略允许该表达式直接在中创建对象str,而不是使用临时+移动。 这对于声明构造函数的情况非常有用