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

版权声明:本文为博主原创文章,转载请注明出处 浅然的专栏 https://blog.csdn.net/w_linux/article/details/83003237

一、场景简述

笔者使用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得到参数值了


三、参考文献

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

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

猜你喜欢

转载自blog.csdn.net/w_linux/article/details/83003237