決解Mybatis傳遞List集合報錯 Available parameters are [collection, list]

完整錯誤如下:
org.apache.ibatis.binding.BindingException: Parameter ‘customerIdList’ not found. Available parameters are [collection, list]

解釋:
當我們傳遞一個 List 實例或者數組作爲參數對象傳給 MyBatis。當你這麼做的時 候,MyBatis 會自動將它包裝在一個 Map 中,用名稱在作爲鍵。List 實例將會以“list” 作爲鍵,而數組實例將會以“array”作爲鍵。所以,當我們傳遞的是一個List集合時,mybatis會自動把我們的list集合包裝成以list爲Key值的map。
錯誤代碼:

DAO 層:
Long selectCustomerCountList( List customerIdList);

XML文件:
<select id="selectCustomerCountList" parameterType="java.util.List" resultType="java.lang.Long">
        select count(1) from np_customer_info where id in
        <foreach item="item" collection="customerIdList" separator="," open="(" close=")" index="">  #{item, jdbcType=INTEGER}    
        </foreach> 
    </select>
==========================
注意:DAO 層接口的參數名與XML 文件中的collection的屬性值一致,是導致的問題的主要原因。

解決方法
第一種:利用Mybatis給我們的封裝進行XML配置,將我們的XML中collection屬性值設置爲list。

DAO 層:
Long selectCustomerCountList( List customerIdList);

XML文件:
<select id="selectCustomerCountList" parameterType="java.util.List" resultType="java.lang.Long">
        select count(1) from np_customer_info where id in
        <foreach item="item" collection="list" separator="," open="(" close=")" index="">  #{item, jdbcType=INTEGER}    
        </foreach> 
    </select>
======================
注意:此時collection強制指定爲list且不可改變

第二種: 利用註解@Param指定我們的入參名稱

DAO層:
Long selectCustomerCountList(@Param("customerIdList") List customerIdList);

XML文件:
<select id="selectCustomerCountList" parameterType="java.util.List" resultType="java.lang.Long">
        select count(1) from np_customer_info where id in
        <foreach item="item" collection="customerIdList" separator="," open="(" close=")" index="">  #{item, jdbcType=INTEGER}    
        </foreach> 
    </select>

======================
注意: 此時的DAO層參數名可以 @Param("customerIdList") 與 collection的屬性值一致

第三種:將我們的List包裝成Map參數進行傳遞

在Service業務處理層次上面將參數進行包裝
public Long selectCustomerCountMap(List customerIdList) {   
        Map maps = new HashMap();
        maps.put("customerIds", customerIdList);
        return customerMapper.selectCustomerCountMap(maps);
    }
    DAO層:
    Long selectCustomerCountMap(Map maps);
XML文件:

<select id="selectCustomerCountMap" parameterType="java.util.Map" resultType="java.lang.Long">
        select count(1) from np_customer_info where id in
        <foreach item="item" collection="customerIds" separator="," open="(" close=")" index="">  #{item, jdbcType=INTEGER}    
        </foreach> 
    </select>
==============
注意: 入參類型是java.util.Map而不再是List ,此時的collection屬性值爲Map中的Key值。

參考文章:http://chenzhou123520.iteye.com/blog/1921284

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章