1. 发生异常的背景
情景:
//在DAO层mapper层中定义的接口
int existIccidCount(List<String> iccidList);
//在Mapper.xml文件中
<select id="existIccidCount" parameterType="java.util.List" resultType="int">
select count(1) from iot_base_card where iccid in
<foreach collection="iccidList" item="iccid" open="(" separator="," close=")">
#{iccid}
</foreach>
</select>
//所抛的异常
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'iccidList' not found. Available parameters are [collection, list]
//发生异常的原因
Caused by: org.apache.ibatis.binding.BindingException: Parameter 'iccidList' not found. Available parameters are [collection, list]
2. 解决方法一
将mapper.xml文件中的List参数的名称改为list。
- 解决原理:
当你传递一个List实例或数组作为参数对象给Mybatis时,Mybatis会自动将它包装在一个Map中,名称根据不同类型而不同。当你的类型是List数组时,key则是list,当你的类型是Array数组,key则是array。自然名称所对应的value是你传进来的实例。
3. 解决方法二
如果你非要想用自己命名的变量名也是可以的,Mybatis还提供了参数绑定的方法用来解决这个问题。
在mapper接口的方法中进行参数绑定。
//修改后的接口
int existIccidCount(@Param("iccidList") List<String> iccidList);
@Param后所跟的变量名必须和Mapper.xml文件中的变量名一样。
本文介绍了解决MyBatis中因参数名称不匹配导致的BindingException异常的方法。通过调整Mapper.xml文件中的参数名称或将参数显式绑定到指定名称,确保List类型的参数能够正确传递。
2万+

被折叠的 条评论
为什么被折叠?



