Mybatis傳遞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值。

  


免責聲明!

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



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