Mybatis传入多个参数报错(组合查询)----解决方法

一、问题引入:

1、我要实现 姓名,年龄段的组合查询功能

【报错】

Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter ‘name’ not found. Available parameters are [arg2, arg1, arg0, param3, param1, param2]

我写的具体代码如下:

1、StudentMapper类:传入 名字,年龄1,年龄2 三个参数

List<Student> getUserByNameAndAge(String name, Integer age1, Integer age2);

2、StudentMapper.xml类:

 <select id="getUserByNameAndAge" resultType="com.csu.software.model.Student">
    select * from student
    <where>
      <if test="name != null">
        and name like CONCAT('%',#{name},'%')
      </if>
      <if test="age1 != null">
        and age &gt; #{age1,jdbcType=INTEGER}
      </if>
      <if test="age2 != null">
        and age &lt; #{age2,jdbcType=INTEGER}
      </if>
   </where>
  </select>

3、报的错误如图所示:
在这里插入图片描述

二、解决的办法

(作者:炫封 原文:https://blog.csdn.net/weixin_37891479/article/details/80525612

产生的原因:
当传入多个参数时,映射文件无法获得传入的参数

AParameter ‘name’ not found. Available parameters are [arg2, arg1, arg0, param3, param1, param2]
这句话的意思就是id找不到,可用的参数是[arg2, arg1, arg0, param3, param1, param2]。
所以可使用参数出现的顺序号码来引用参数,第一个参数用arg0或param1表示,第二个参数用arg1或param2表示,

方法1,利用参数出现的顺序:

StudentMapper不变, 只修改StudentMapper.xml文件,注意,将name改成arg0,age1改成arg1,age2改成arg2

<select id="getUserByNameAndAge" resultType="com.csu.software.model.Student">
    select * from student
    <where>
      <if test="arg0 != null">
        and name like CONCAT('%',#{arg0},'%')
      </if>
      <if test="arg1 != null">
        and age &gt; #{arg1,jdbcType=INTEGER}
      </if>
      <if test="arg2 != null">
        and age &lt; #{arg2,jdbcType=INTEGER}
      </if>
    </where>
  </select>

方法2,使用注解

StudentMapper.xml文件不变,修改StudentMapper

List<Student> getUserByNameAndAge(@Param("name") String name, @Param("age1") Integer age1, @Param("age2") Integer age2);

方法3,把接口的形参改为Map

StudentMapper.xml文件不变,修改StudentMapper, UserServiceImpl

//StudentMapper接口:
List<Student> getUserByNameAndAge(Map params);
//UserServiceImpl:
Map params = new HashMap();
params.put("name", name);
params.put("age", age1);
params.put("age", age2);
List<Student> list = studentMapper.getUserByNameAndAge(params);
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值