MyBatis傳入數組和列表時的處理方案

List<User> selectByUserIdList(@Param("userIds")String[] userIds);

因要查看userId在userIds這個範圍內,因此需要使用in關鍵字。那麼數組是怎麼在mybatis文件中使用的呢?

<select id="selectByRoleIdList" resultMap="user" >
SELECT * FROM user
    <if test="userIds!= null">
        where user_id in(
            <foreach collection="userIds" item="userId" index="index" separator="," >  
                #{userId,jdbcType=INTEGER} 
            </foreach>
        )   
    </if>

注意:這裏的collection是你集合的字段名。在使用的時候,曾經按照網上說的,在這裏寫的是array。但是啓動時報錯nested exception is org.apache.ibatis.binding.BindingException: Parameter ‘array’ not found. 萬望注意

List<User> selectByRoleIdList1(@Param("userIds")List<String> userIds);

當入參是集合時,原則上跟數組的情況是一樣的。

<select id="selectByRoleIdList1" resultMap="user" >
SELECT * FROM user
    <if test="userIds!= null">
        where user_id in(
            <foreach collection="userIds" item="userId" index="index" separator="," >  
                #{userId,jdbcType=INTEGER} 
            </foreach>
        )   
    </if>

在mybatis的mapper配置文件中,可以利用<foreach>標籤實現sql條件的循環,可完成類似批量的sql
mybatis接受的參數分爲:(1)基本類型(2)對象(3)List(4)數組(5)Map
無論傳哪種參數給mybatis,他都會將參數放在一個Map中:
如果傳入基本類型:變量名作爲key,變量值作爲value 此時生成的map只有一個元素。
如果傳入對象: 對象的屬性名作爲key,屬性值作爲value
如果傳入List: “list”作爲key,這個List是value (這類參數可以迭代,利用<foreach>標籤實現循環)
如果傳入數組: “array”作爲key,數組作爲value(同上)
如果傳入Map: 鍵值不變。


<foreach>標籤的用法:
collection:要循環的集合
index:循環索引(不知道啥用。。)
item:集合中的一個元素(item和collection,按foreach循環理解)
open:以什麼開始
close:以什麼結束
separator:循環內容之間以什麼分隔

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