1、批量插入
<insert
id="insertBatch"
parameterType="java.util.List">
insert into
t_student(name, age, class)
values
<foreach
collection="list"
item="item"
index="index"
separator=",">
(
#{item.name,jdbcType=VARCHAR},
#{item.age,jdbcType=INTEGER},
#{item.class,jdbcType=LONGVARCHAR}
)
</foreach>
</insert>
2、批量更新
方式一:
<update id="updateBatch">
<foreach
collection="list"
separator=";"
item="stud">
update t_studetn set
name = #{stud.name},
age = #{stud.age},
class = #{stud.sex},
where id = #{stud.id}
</foreach>
</update>
方式二:
<update>
id="updateBatch"
parameterType="list">
UPDATE t_student
SET name = CASE id
<foreach
collection="list"
item="i"
index="index">
WHEN #{i.id} THEN #{i.name}
</foreach>
END,
age = CASE id
<foreach
collection="list"
item="i"
index="index">
WHEN #{i.id} THEN #{i.age}
</foreach>
END
WHERE id IN
<foreach
collection="list"
separator="or"
item="i"
index="index" >
id=#{i.id}
</foreach>
</update>
3、批量删除
<delete id="deleteBatchByParams">
delete from
t_student
where
id IN
<foreach
collection="ids"
item="item"
index="index"
open="(" close=")"
separator=",">
#{item}
</foreach>
</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,該參數可選。 |
本文作者: java樂園
本文來自雲栖社群合作夥伴“
JAVA樂園”,了解相關資訊可以關注“
”