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));尤其需要注意;
 


免責聲明!

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



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