Mybatis中使用foreach標簽出現的錯誤


錯誤原因:

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

代碼如下:

dao:

public List<Employee> getEmpsByConditionForeach(List<Integer> ids);

xml:

<select id="getEmpsByConditionForeach" resultType="com.fenga.mybatis.bean.Employee">
        select * from tbl_employee
         <!--
             collection:指定要遍歷的集合:
                 list類型的參數會特殊處理封裝在map中,map的key就叫list
             item:將當前遍歷出的元素賦值給指定的變量
             separator:每個元素之間的分隔符
             open:遍歷出所有結果拼接一個開始的字符
             close:遍歷出所有結果拼接一個結束的字符
             index:索引。遍歷list的時候是index就是索引,item就是當前值
                           遍歷map的時候index表示的就是map的key,item就是map的值
             
             #{變量名}就能取出變量的值也就是當前遍歷出的元素
           -->
         <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<Employee> 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<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);

 結果如圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM