屬性 | 描述 |
---|---|
item | 循環體中的具體對象。支持屬性的點路徑訪問,如item.age,item.info.details。 具體說明:在list和數組中是其中的對象,在map中是value。 該參數爲必選。 |
collection | 要作foreach的對象,做爲入參時,List<?>對象默認用list代替做爲鍵,數組對象有array代替做爲鍵,Map對象用map代替做爲鍵。 固然在做爲入參時能夠使用@Param("keyName")來設置鍵,設置keyName後,list,array,map將會失效。 除了入參這種狀況外,還有一種做爲參數對象的某個字段的時候。舉個例子: 若是User有屬性List ids。入參是User對象,那麼這個collection = "ids" 若是User有屬性Ids ids;其中Ids是個對象,Ids有個屬性List id;入參是User對象,那麼collection = "ids.id" 上面只是舉例,具體collection等於什麼,就看你想對那個元素作循環。 該參數爲必選。 |
separator | 元素之間的分隔符,例如在in()的時候,separator=","會自動在元素中間用「,「隔開,避免手動輸入逗號致使sql錯誤,如in(1,2,)這樣。該參數可選。 |
open | foreach代碼的開始符號,通常是(和close=")"合用。經常使用在in(),values()時。該參數可選。 |
close | foreach代碼的關閉符號,通常是)和open="("合用。經常使用在in(),values()時。該參數可選。 |
index | 在list和數組中,index是元素的序號,在map中,index是元素的key,該參數可選。 |
1.select count(*) from users id in (x1,x2,x3,...)
<select id="countByUserList" resultType="int" parameterType="list"> select count(*) from users <where> id in <foreach item="item" collection="list" separator="," open="(" close=")" index=""> #{item.id, jdbcType=NUMERIC} </foreach> </where> </select>
2.循環插入表數據,用到dual僞表給數據作掩護。
insert into deliver (col1,col2,col3,col4,...) select col1,col2,col3,col4... from dual union all select col11,col22,col33,col44,... from dual。(字段col1,col2,col3,col4,...)添加
或者
insert into deliver select col1,col2,col3,col4,... from dual union all select col11,col22,col33,col44,... from dual。(所有字段添加)
<insert id="addList"> INSERT INTO DELIVER ( <include refid="selectAllColumnsSql"/> ) <foreach collection="deliverList" item="item" separator="UNION ALL"> SELECT #{item.id, jdbcType=NUMERIC}, #{item.name, jdbcType=VARCHAR} FROM DUAL </foreach> </insert>
3.循環插入map值 insert into users(key,values) values(key1,values1),(key2,values3),(key3,values4)sql
<insert id="ins_string_string"> insert into string_string (key, value) values <foreach item="item" index="key" collection="map" open="" separator="," close="">(#{key}, #{item})</foreach> </insert>
4.select count(*) from key_cols where col_a = ? AND col_b = ?數組
(必定要注意到$和#的區別,$的參數直接輸出,#的參數會被替換爲?,而後傳入參數值,加上' '後執行。能夠防止sql注入)app
<select id="sel_key_cols" resultType="int"> select count(*) from key_cols where <foreach item="item" index="key" collection="map" open="" separator="AND" close="">${key} = #{item}</foreach> </select>
5.select * from t_news n where n.tags like ? or n.tags like ? spa
<select id="selectTestForEach" parameterType="News" resultMap="NewsResultMapper"> select * from t_news n where <foreach collection="listTag" index="index" item="tag" open="" separator="or" close=""> n.tags like '%'||#{tag}||'%' </foreach> <select>