Mybatis 报错: Parameter ‘xxx‘ not found. Available parameters are [collection, list]

本文介绍了MyBatis在处理集合参数时的内部机制,当传入参数为集合时,MyBatis会将其封装到Map中,key默认为'list'。在XML映射文件中,使用<foreach>标签遍历集合时,需确保collection属性与Map中的key一致。文中通过一个具体的例子展示了由于collection属性设置错误导致的异常,并提供了修正后的正确写法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mapper.java

public interface MyBlogMapper {
    List<MyBlog> selectByIds(List<Long> ids);
}

mapper.xml

 <select id="selectByIds" resultType="org.apache.ibatis.example.domain.MyBlog">
    select * from my_blog
    <where>
        id in
        <foreach collection="ids" open="(" close=")" separator="," item="idValue">
          #{idValue}
        </foreach>
    </where>
  </select>

测试

 @Test
    public void testCollectionTag() {
        List<Long> ids = new ArrayList<>();
        ids.add(1L);
        ids.add(2L);
        List<MyBlog> myBlogList = mapper.selectByIds(ids);
    }

运行结果

在这里插入图片描述

源码分析

根据控制台报错, 定位到抛异常的那一行代码

return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
private Object wrapCollection(final Object object) {
    if (object instanceof Collection) {
      StrictMap<Object> map = new StrictMap<Object>();
      map.put("collection", object);
      if (object instanceof List) {
        map.put("list", object);
      }
      return map;
    } else if (object != null && object.getClass().isArray()) {
      StrictMap<Object> map = new StrictMap<Object>();
      map.put("array", object);
      return map;
    }
    return object;
  }

根据该段代码可知, 当我们 mapper 方法中的参数是一个集合时, mybatis 会把这个集合参数重新封装到一个 map中, 而 map 中这个集合对应的key 写死成了 list.

然而我们 mapper.xml 中, 用的是 ids. map 中根本不存在这个 key, 所以就间接触发了标题中所描述的异常.

 <select id="selectByIds" resultType="org.apache.ibatis.example.domain.MyBlog">
    select * from my_blog
    <where>
        id in
        <foreach collection="ids" open="(" close=")" separator="," item="idValue">
          #{idValue}
        </foreach>
    </where>
  </select>

正确的写法

ids 改成 list

 <select id="selectByIds" resultType="org.apache.ibatis.example.domain.MyBlog">
    select * from my_blog
    <where>
        id in
        <foreach collection="list" open="(" close=")" separator="," item="idValue">
          #{idValue}
        </foreach>
    </where>
  </select>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值