foreach屬性
屬性 | 描述 |
---|---|
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)
<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注入)
<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 ?
<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>