MyBatis 報錯Parameter 'mobile' not found. Available parameters are [arg1, arg0, param1, param2]解決方案
阿新 • • 發佈:2018-12-16
一、場景簡述
筆者使用MyBatis 3.x的時候使用如下介面
@Mapper public interface UserMapper { @Select("select id,mobile,password from news_user where mobile = #{mobile} and password = #{password}") List<UserBean> selectUser(String mobile,String password); @Select("select id,mobile,password from news_user where mobile = #{mobile}") List<UserBean> selectUser1(String mobile); }
但是,在單元測試的時候報錯,報錯資訊如下
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'mobile' not found. Available parameters are [arg1, arg0, param1, param2]
二、解決方案
在MyBatis3.4.4版不能直接使用#{0}要使用 #{arg0} 或使用@Param,可以看到報錯提示中也已經給出提示
1、使用#{arg0}
@Mapper public interface UserMapper { @Select("select id,mobile,password from news_user where mobile = #{arg0} and password = #{arg1}") List<UserBean> selectUser(String mobile,String password); @Select("select id,mobile,password from news_user where mobile = #{arg0}") List<UserBean> selectUser1(String mobile); }
2、使用@Param
@Mapper
public interface UserMapper {
@Select("select id,mobile,password from news_user where mobile = #{mobile} and password = #{password}")
List<UserBean> selectUser(@Param("mobile") String mobile, @Param("password") String password);
@Select("select id,mobile,password from news_user where mobile = #{mobile}")
List<UserBean> selectUser1(@Param("mobile") String mobile);
}
where mobile = #{mobile} and password = #{password}表示sql語句要接受2個引數
一個引數名是mobile,一個引數名是password,如果要正確的傳入引數,那麼就要給引數命名,
因為不用xml配置檔案,那麼我們就要用別的方式來給引數命名,這個方式就是@Param註解
在方法引數的前面寫上@Param("引數名"),表示給引數命名,名稱就是括號中的內容
selectUser(@Param("mobile") String mobile, @Param("password") String password);
給入參 String mobile 命名為mobile,然後sql語句....where mobile= #{mobile} 中就可以根據mobile得到引數值了