MyBatis 报错Parameter 'mobile' not found. Available parameters are [arg1, arg0, param1, param2]解决方案

冷不防 2022-05-08 09:44 418阅读 0赞

一、场景简述

笔者使用MyBatis 3.x的时候使用如下接口

  1. @Mapper
  2. public interface UserMapper {
  3. @Select("select id,mobile,password from news_user where mobile = #{mobile} and password = #{password}")
  4. List<UserBean> selectUser(String mobile,String password);
  5. @Select("select id,mobile,password from news_user where mobile = #{mobile}")
  6. List<UserBean> selectUser1(String mobile);
  7. }

但是,在单元测试的时候报错,报错信息如下

  1. 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}

  1. @Mapper
  2. public interface UserMapper {
  3. @Select("select id,mobile,password from news_user where mobile = #{arg0} and password = #{arg1}")
  4. List<UserBean> selectUser(String mobile,String password);
  5. @Select("select id,mobile,password from news_user where mobile = #{arg0}")
  6. List<UserBean> selectUser1(String mobile);
  7. }

2、使用@Param

  1. @Mapper
  2. public interface UserMapper {
  3. @Select("select id,mobile,password from news_user where mobile = #{mobile} and password = #{password}")
  4. List<UserBean> selectUser(@Param("mobile") String mobile, @Param("password") String password);
  5. @Select("select id,mobile,password from news_user where mobile = #{mobile}")
  6. List<UserBean> selectUser1(@Param("mobile") String mobile);
  7. }

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得到参数值了


三、参考文献

https://blog.csdn.net/q1035331653/article/details/80712845

https://www.cnblogs.com/thomas12112406/p/6217211.html

发表评论

表情:
评论列表 (有 0 条评论,418人围观)

还没有评论,来说两句吧...

相关阅读