Foreach的基本結構以下:java
<foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach>
Item:表示迭代的項,#{item}表明是傳進來集合中相應位置的值sql
Index:表示集合如今迭代的位置數組
open:迭代開始以前添加的值spa
close:迭代結束以後添加的值code
collection:從字面上的意思就能夠看出來是一個集合,它是必須有的,它表明着一個集合,它的取值有3種狀況。get
一、 list 表示方法傳進來的參數是一個List集合it
public List<User> getUsersByIds(List<Long> ids);
<select id="getUsersByIds" resultType="User"> SELECT * FROM user WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
二、 array表示方法傳進來的參數是一個數組io
public List<User> getUsersByIds(Long [] ids);class
<select id="getUsersByIds" resultType="User"> SELECT * FROM user WHERE ID in <foreach item="item" index="index" collection="array" open="(" separator="," close=")"> #{item} </foreach> </select>
三、 map的鍵(key),這個key在map中對應的值是一個集合。foreach
public List<User> getUsersByIds(Map<String,Object> map);
<select id="getUsersByIds" resultType="User"> SELECT * FROM user WHERE ID in <foreach item="item" index="index" collection="ids" open="(" separator="," close=")"> #{item} </foreach> </select>
對於參數是map ,映射語句中的collection的值ids在map中對應的鍵的值必須是一個集合或者數組。
假設咱們的集合中的包含1,3,5,7,9。那麼上面3種狀況下最終組合出來的語句是:
select * from user where ID in(1,3,5,7,9)