Mybatis中使用foreach标签出现的错误


错误原因:

Cause: org.apache.ibatis.binding.BindingException: Parameter 'ids' not found. Available parameters are [arg0, collection, list]

代码如下:

dao:

public List getEmpsByConditionForeach(List ids);

xml:

<select id="getEmpsByConditionForeach" resultType="com.fenga.mybatis.bean.Employee">
        select * from tbl_employee
         
         <foreach collection="ids" item="item_id" separator=","
             open="where id in(" close=")">
             #{item_id}
         foreach>
    select>

Test:

@Test
    public void test1() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        
        try {
            EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
            
            List list = mapper.getEmpsByConditionForeach(Arrays.asList(1,2,3));
            for (Employee emp : list) {
                System.out.println(emp);
            }
            
        }finally {
            openSession.close();
        }
        
    }

解决问题:

  Parameter 'ids' not found. 意思是没找到ids这个集合,可以通过@Param给集合命名,如下:

public List getEmpsByConditionForeach(@Param("ids")List ids);

 结果如图