mybatis关于出现Parameter 'noList' not found. Available parameters are [collection, list]问题的解决方案

当我们要查询一些人的信息时,但这些人的id是由用户确定的,就会采用list集合或者数组作为参数传入方法中,

public List findSomeUsers(List noList);

而在xml文件中就可以用Forreach动态SQL解决

<select id="findSomeUsers" resultType="user3" parameterType="list">
	select * from user where id in
	<foreach collection="noList" index="index" item="no" open="(" separator="," close=")">
		#{no}
	</foreach>
</select>

测试代码:

List<Integer> noList = new ArrayList<>();
noList.add(1);
noList.add(2);
noList.add(3);
noList.add(6);
List<User> list = mapper.findSomeUsers(noList);

结果却出错了,原因是找不到noList这个参数,为什么呢?
接着我在接口方法中的参数前面用注解的方式加上了@Param(“noList”),接着测试了一下,
结果并没有报错,且查出了结果
sql语句是select * from user where id in ( ? , ? , ? , ? )

User [id=1, name=张三, age=23]
User [id=2, name=李四, age=30]
User [id=3, name=张无忌, age=30]
User [id=6, name=张良, age=30]

然后上网查了一下,还有一种说法是:
因为 传递一个 List 实例或者数组作为参数对象传给 MyBatis,MyBatis 会自动将它包装在一个 Map 中,用名称在作为键。List 实例将会以“list” 作为键,而数组实例将会以“array”作为键

接着我恢复了之前发生错误的环境,把xml中的foreach中的collection改成了list,其他的都没改,没有报错,也可以查询出结果。

因此,解决这个异常的两种方式是:
1.在方法参数前面加上你遍历的集合的名称,比如你在foreach的collection中写的是noList,那么你就在传入的list参数前面加上一个注解@Param(“noList”)。
2.将foreach的collection中的值改成list即可。


版权声明:本文为qq_37745636原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。