問題:
org.mybatis.spring.MyBatisSystemException:nested exception is org.apache.ibatis.binding.BindingException: Parameter 'xxx' not found. Available parameters are [arg1, arg0, param1, param2]
原因:
這個問題是因為我們在Mapper接口中聲明方法的時候有多個參數,例如:
Mapper接口中方法:
int selectUser(String pid,String pname);
然后在mapper.xml配置如下:
<select id="selectUser" resultType="xxx.xxx.xxx.model.User">
select *
from user
where id = #{pid} and name = #{pname}
</select>
這樣直接用pid,pname就會報錯的。
解決方法:
這里使用@Param注解,這種方式Mybatis就會自動將參數封裝成Map類型,@Param注解的值會作為Map中的key,例如:
Mapper接口中:
int selectUser(@Param("pid")String pid,@Param("pn")String pname);
mapper.xml中:
<select id="selectUser" resultType="xxx.xxx.xxx.model.User">
select *
from user
where id = #{pid} and name = #{pn}
</select>
這里注意一下:
@Param(“pn”) String pname,@Param里面的定義的名稱(即pn)可以和參數名(即pname)不一致。在xml中的SQL 語句是以“pn”作為key的。也就是說在使用時是 name = #{pn},而不是 name = #{pname}了。