foreach標簽主要用於構建in條件,他可以在sql中對集合進行迭代。如下:
<delete id="deleteBatch">
delete from user where id in
<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
我們假如說參數為---- int[] ids = {1,2,3,4,5} ----那么打印之后的SQL如下:
delete form user where id in (1,2,3,4,5)
釋義:
collection :collection屬性的值有三個分別是list、array、map三種,分別對應的參數類型為:List、數組、map集合,我在上面傳的參數為數組,所以值為array
item : 表示在迭代過程中每一個元素的別名
index :表示在迭代過程中每次迭代到的位置(下標)
open :前綴
close :后綴
separator :分隔符,表示迭代時每個元素之間以什么分隔
我們通常可以將之用到批量刪除、添加等操作中。
再比如
查詢:
<!-- 獲取商戶對賬單的fileId -->
<select id="getBillInfoList" resultType="com.wondersgroup.soa.dto.bill.BillInfoEntity">
select *
from t_mer_file_mer_info
where batchNo in
<foreach collection="list" item="batchNo" index="index"
open="(" close=")" separator=",">
#{batchNo}
</foreach>
</select>
插入:
<insert id="batchinsertSelective" parameterType="tPortalAdjunctEntity" >
insert into t_portal_adjunct (merno, type,type_id, file_id, file_name)
values
<foreach collection ="list" item="info" index= "index" separator =",">
(#{info.merno}, #{info.type},
#{info.type_id}, #{info.file_id}, #{info.file_name})
</foreach >
</insert>