mybatis動態sql中foreach標簽的使用


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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM