MyBatis(映射文件中使用foreach標簽時報錯,屬性collection的問題)


org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: org.apache.ibatis.binding.BindingException: Parameter 'ids' not found. Available parameters are [collection, list]
### Cause: org.apache.ibatis.binding.BindingException: Parameter 'ids' not found. Available parameters are [collection, list]

在學習mybatis的時候,使用foreach遍歷集合,出現上述一樣的錯誤

接口代碼:

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

xml代碼:

    <!--多個id查詢信息===id in (1,2,3)-->
    <select id="getEmpsbyCondtionForeach" resultType="emp">
        select * from tbl_employee where id in
        <!-- collection:指定要遍歷的集合:
                list類型的參數會特殊處理封裝在map中,map的key就是list
             item:將當前遍歷出的元素賦值給指定的變量
             separator:每個元素之間的分隔符
             open:遍歷出所有結果拼接一個開始的字符
             close:遍歷出所有結果拼接一個結束的字符
             index:索引。遍歷list的時候是index就是索引,item就是當前值
                         遍歷map時index表示的就是map的key,item就是map的值

             #{變量名}就能取出變量值,也就是當前遍歷出的元素
         -->
        <foreach collection="id" item="item_id" separator=","
                open="(" close=")">
            #{item_id}
        </foreach>
    </select>

解決方案:

修改mapper.java:

    public List<Employee> getEmpsbyCondtionForeach(@Param("ids") List<Integer> ids);

或者修改mapper.xml:

    <!--多個id查詢信息===id in (1,2,3)-->
    <select id="getEmpsbyCondtionForeach" resultType="emp">
        select * from tbl_employee where id in
        <!-- collection:指定要遍歷的集合:
                list類型的參數會特殊處理封裝在map中,map的key就是list
             item:將當前遍歷出的元素賦值給指定的變量
             separator:每個元素之間的分隔符
             open:遍歷出所有結果拼接一個開始的字符
             close:遍歷出所有結果拼接一個結束的字符
             index:索引。遍歷list的時候是index就是索引,item就是當前值
                         遍歷map時index表示的就是map的key,item就是map的值

             #{變量名}就能取出變量值,也就是當前遍歷出的元素
         -->
        <foreach collection="list" item="item_id" separator=","
                open="(" close=")">
            #{item_id}
        </foreach>
    </select>

原因:

foreach標簽的屬性collection,在不同的情況下,該屬性的值是不一樣的,主要有以下3種情況:

1、如果傳入的是單參數且參數類型是一個List的時候,collection屬性值為list。

2、如果傳入的是單參數且參數類型是一個array數組的時候,collection的屬性值為array。

3、如果傳入的參數是多個的時候,我們就需要把它們封裝成一個Map,當然單參數也可以封裝成Map,實際上如果你在傳入參數的時候,在MyBatis里面也是會把它封裝成一個Map的,map的key就是參數名,所以這個時候collection屬性值就是傳入的List或array對象在自己封裝的map里面的key。

 

 

 

 

 

 

 

 

 

 


免責聲明!

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



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