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

本文详细介绍了在使用MyBatis3.x进行单元测试时遇到的参数命名错误,并提供了两种解决方案:使用#{arg0}

一、场景简述

笔者使用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.youkuaiyun.com/q1035331653/article/details/80712845

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值