mybatis {arg0} 与 {0}

解决方案:

MyBatis的XML的配置文件中声明设置属性的useActualParamName参数值为假

<setting name="useActualParamName" value="false" />

代码展示:

Dao层函数

User getUserBys(int id,String name);

对应的mapping.xml

 
<select id="getUserBys" resultType="model.User">
 
select * from user where id = #{0} and name=#{1}
 
</select>

这种方法应该是对的,但是如果你使用的是mybatis3.4.2或者之后的版本,就会产生绑定异常:

org.apache.ibatis.binding.BindingException: Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]

从异常可以看出在没有使用@参数注解的情况下,传递参数需要使用

#{}为arg0 - #{} ARGN#或者{}参数1 - #{} paramn

  • 更换下mapping.xml中的代码
<select id="getUserBys" resultType="model.User">
 
select * from user where id = #{arg0} and name=#{arg1}
 
</select>

此时代码就会正常运行


下面贴上3.4.1以及之前版本的绑定异常信息:

 org.apache.ibatis.binding.BindingException: Parameter 'arg0' not found. Available parameters are [0, 1, param1, param2]

可以发现3.4.1版本中传递参数可以使用#{0} - #{N}

问题原因

MyBatis的通过XMLConfigBuilder类来加载配置文件中的各项参数

  • 3.4.2版本之前设置属性中useActualParamName参数的默认值为flase 
    XMLConfigBuilder.class的settingsElement方法中的源代码
configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
  • 3.4.2版本之后设置属性中useActualParamName参数的默认值为true 
    XMLConfigBuilder.class的settingsElement方法中的源代码
configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), false));
原文地址:https://www.cnblogs.com/zhangmingcheng/p/9922236.html