Mybatis_批量操作

  • 批量删除
int batchDel(int[] userIds);
<delete id="batchDel">
	<!-- delete from user where user_id in (?,?,?) -->
	delete 
	from 
		user
	where 
		user_id in
		<!-- foreach 循环 动态生成sql
			collection - 
				如果传入参数是集合或数组:数组 array 列表 list 集合 set
				如果传入的参数是一个对象而集合或数组是该对象的一个属性时,这里就写属性的名字 
			open 以什么字符串开始	
			close 以什么字符串结尾
			item 遍历取出的元素的名字
			separator 表示元素之间的分隔符
		 -->
		<foreach collection="array" open="(" close=")" item="userId" separator=",">
			#{userId}
		</foreach>
</delete>
  • 批量新增
/**
* 批量新增
 * 
 * insert into table (col1,col2,...) values (?,?,...),(?,?,...),(?,?,...),(?,?,...)
 * insert into table (col1,col2,...) select * from ... 
 * @param users
 * @return
 */
int batchInsert(List<User> users);
<!-- 批量新增 -->
<insert id="batchInsert">
 	insert into user (username,password,sex,createtime) 
 	<!-- 批量新增语句1  mysql独有 -->
 	values
 	<foreach collection="list" item="user" separator=",">
 		(#{user.username},#{user.password},#{user.sex},#{user.createtime})
 	</foreach> 
 	<!-- 批量新增语句2  mysql独有 -->
 	<foreach collection="list" item="user" separator="union">
 		select #{user.username},#{user.password},#{user.sex},#{user.createtime} from dual
 	</foreach>
 </insert>
  • 批量修改
/**
* 批量修改
 * 
 * update table set col1 = case table_id when 值1 then 值11 when 值2 then 值22 else col1 end,
 * col2 = case table_id when 值1 then 值11 when 值2 then 值22 else col1 end
 * where
 * 	table_id in (值1,值2,... )
 * 
 * @param users
 * @return
 */
int batchUpdate(List<User> users);
<update id="batchUpdate">
	update user
	set sex = 
	<foreach collection="list" item="user" open="case user_id" close="end">
		when #{user.userId} then #{user.sex}
	</foreach>
	where
		user_id
		in
		(
		<foreach collection="list" item="user" separator=",">
			#{user.userId}
		</foreach>
		)
</update>
发布了340 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Chill_Lyn/article/details/103752601