foreach 也就是遍歷迭代,在SQL中通常用在 in 這個關鍵詞的后面
foreach元素的屬性主要有 item,index,collection,open,separator,close。
分別代表:
item表示集合中每一個元素進行迭代時的別名,
index用於表示在迭代過程中,每次迭代到的位置,
open表示該語句以什么開始,
separator表示在每次進行迭代之間以什么符號作為分隔 符,
close表示以什么結束
代碼片段:
<select id="selectByIds" resultType="com.wuuushao.pojo.User"> select * from user where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
而最為重要的就是collection屬性了,既然是迭代就表示傳入的參數是多個,這時候傳入的參數就有以下幾種可能:
- list
- array
- map
下面針對這三種情況進行具體的介紹
傳入的參數為list的時候
對應的Mapper.java文件是:
public List<User> selectByIds(List<Integer> ids);
xml文件代碼片段:
<select id="selectByIds" resultType="com.jackpotHan.pojo.User"> select * from user where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
傳入的參數為Array的時候
對應的Mapper.java文件是:
public List<User> selectByIds(int[] ids);
xml文件代碼片段:
<select id="selectByIds" resultType="com.jackpotHan.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.jackpotHan.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));這個不是隨便亂寫的,尤其需要注意;
