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情况比较复杂,这里不做讲解





https://blog.csdn.net/czd3355/article/details/75340080

https://blog.csdn.net/isea533/article/details/21237175?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

猜你喜欢

转载自blog.csdn.net/weixin_42950079/article/details/106294045