1. 程式人生 > >MyBatis:SQL語句中的foreach標籤的詳細介紹

MyBatis:SQL語句中的foreach標籤的詳細介紹

foreach 也就是遍歷迭代,在SQL中通常用在 in 這個關鍵詞的後面

foreach元素的屬性主要有 item,index,collection,open,separator,close。

分別代表:

item表示集合中每一個元素進行迭代時的別名,

index用於表示在迭代過程中,每次迭代到的位置,

open表示該語句以什麼開始,

separator表示在每次進行迭代之間以什麼符號作為分隔 符,

close表示以什麼結束

程式碼片段:

<select id="selectByIds" resultType="com.txw.pojo.User">

        select * from user where id in

        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">

            #{item}

        </foreach>

</select>

而最為重要的就是collection屬性了,既然是迭代就表示傳入的引數是多個,這時候傳入的引數就有以下幾種可能:

1. 傳入的引數為list的時候

 對應的Dao中的Mapper檔案是:

public List<User> selectByIds(List<Integer> ids);

xml檔案程式碼片段:

<select id="selectByIds" resultType="com.txw.pojo.User">

        select * from user where id in

        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">

            #{item}

        </foreach>

</select>

2. 傳入的引數為Array的時候

對應的Dao中的Mapper檔案是:

public List<User> selectByIds(int[] ids);

xml檔案程式碼片段: 

<select id="selectByIds" resultType="com.txw.pojo.User">

        select * from user where id in

        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">

            #{item}

        </foreach>

    </select>

3. 傳入的引數為Map的時候

對應的Dao中的Mapper檔案是:

public List<User> selectByIds(Map<String, Object> params);

xml檔案程式碼片段: 

<select id="selectByIds" resultType="com.txw.pojo.User">

        select * from user where  id in

        <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">

            #{item}

        </foreach>

    </select>

map的時候需要注意的是:collection的值“ids”是儲存在map中的key(比如:map.put("ids",ids));尤其需要注意;