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>
對應的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的時候
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>