MySQL批量插入、批量更新及批量刪除語句


1、批量插入

  1. <insert
  2. id= "insertBatch"
  3. parameterType= "java.util.List">
  4. insert into
  5. t_student(name, age, class)
  6. values
  7. <foreach collection="list" item="item" index="index" separator=",">
  8. (
  9. #{item.name,jdbcType=VARCHAR},
  10. #{item.age,jdbcType=INTEGER},
  11. #{item.class,jdbcType=LONGVARCHAR}
  12. )
  13. </ foreach>
  14. </insert>

2、批量更新

方式一:

  1. <update id= "updateBatch">
  2. < foreach collection="list" separator=";" item="stud">
  3. update t_studetn set
  4. name = #{stud.name},
  5. age = #{stud.age},
  6. class = #{stud.sex},
  7. where id = #{stud.id}
  8. </ foreach>
  9. </update>

方式二:

  1. <update id= "updateBatch" parameterType="list">
  2. UPDATE t_student
  3. SET name = CASE id
  4. <foreach collection= "list" item="i" index="index">
  5. WHEN #{i.id}
  6. THEN #{i.name}
  7. </foreach>
  8. END,
  9. age = CASE id
  10. <foreach collection= "list" item="i" index="index">
  11. WHEN #{i.id} THEN #{i.age}
  12. </foreach>
  13. END
  14. WHERE id IN
  15. <foreach collection= "list" separator="or" item="i" index="index" >
  16. id= #{i.id}
  17. </foreach>
  18. </update>

3、批量刪除

  1. < delete id="deleteBatchByParams">
  2. delete from
  3. t_student
  4. where
  5. id IN
  6. < foreach collection="ids" item="item" index="index" open="("close=")"separator=",">
  7. #{item}
  8. < /foreach>
  9. </delete>

 

 

item 循環體中的具體對象。支持屬性的點路徑訪問,如item.age,item.info.details。
具體說明:在list和數組中是其中的對象,在map中是value。
該參數為必選。
collection

要做foreach的對象,作為入參時,List<?>對象默認用list代替作為鍵,數組對象有array代替作為鍵,Map對象沒有默認的鍵。
當然在作為入參時可以使用@Param("keyName")來設置鍵,設置keyName后,list,array將會失效。 除了入參這種情況外,還有一種作為參數對象的某個字段的時候。舉個例子:
如果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,該參數可選。
 

https://blog.csdn.net/u014252478/article/details/91386289


免責聲明!

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



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