MyBatis複習(七):MyBatis批量處理

foreach元素屬性

foreach是動態SQL的一個重要元素,我們可以將任何可迭代對象(List、Set等)、Map對象或數組對象作爲集合參數傳遞給foreach,然後通過迭代傳入的集合參數進行批量操作處理。

  • 當使用可迭代對象或數組時:index 代表當前迭代的序號,item的值是本次迭代獲取到的元素。

  • 當使用Map對象時,index是鍵,item是值

  • collection:表示傳入的參數類型

    • 如果參數類型是List,則collecion屬性值必須指定爲list,即collection="list"

    • 如果參數類型是Array,則collecion屬性值必須指定爲array,即collection="array"

    • 如果參數類型爲Map,則collecion屬性值

  • item:item是循環體中的具體對象。例如 item.title ,item.content ,item.description , item.createTime

    • 在List和數組中,item表示本次迭代獲取到的元素。

    • 在Map中,item表示map中鍵的值。

  • index:在List和數組中,index表示元素的序號;在Map中,index表示元素的key

  • open:開頭字符,一般與close=")"合用,常用在in()子句中

  • close:結尾字符,一般與open="("合用,常用在in()子句中

  • separator:集合項迭代之間的分隔符。例如separator=",“會自動在元素中間用”,"隔開,如values(“a”,“b”),(“a”,“b”) 或 in(“a”, “b”)


批量插入

SQL語法格式:

insert into t_table(col_1, col_2, col_3) values("a1","b1","c1"),("a2","b2","c2"), ..., ("an","bn","cn")

MyBatis中的用法:

<insert id="batchInsert" parameterType="java.util.List">
	insert into t_blog(title, content, description, create_time)
	values
	<foreach collection="list" item="item" index="index" separator=",">
		#{item.title}, #{item.content}, #{item.description}, #{item.createTime}
	</foreach>
</insert >

批量刪除

SQL語法格式:

delete from t_table where col_1 in (value_1, value_2, ..., value_n)

MyBatis中的用法:

<delete id="batchDelete" parameterType="java.util.List">
	delete from t_blog where blog_id in
	<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
		#{item}
	</foreach>
</delete >

批量查詢

SQL語法格式:

select col_n from t_table where col_m in (value_1, value_2, ..., value_n)

MyBatis中的用法:

<select id="batchSelect" resultType="User">
	select username from t_user where age in
	<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
		#{item}
	</foreach>
</delete >



參數是List類型
<select id="batchSelect" resultType="User">
	select username from t_user where age in
	<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
		#{item}
	</foreach>
</delete >

參數是Array類型
<select id="batchSelect" resultType="User">
	select username from t_user where age in
	<foreach collection="array" item="item" index="index" open="(" close=")" separator=",">
		#{item}
	</foreach>
</delete >

參數是Map類型

map情況比較複雜,這裏不做講解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章