版权声明:本文为博主原创文章,转载请注明出处 浅然的专栏 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得到参数值了