我们在批量的要新增修改或者删除一些数据库时,会使用单条sql语句来完成批量操作,这种方式比使用循环的方式,单条操作效率会提高很多,本篇文章就介绍下使用mybatis来完成批量操作。假设我们有如下表(建表sql语句):
CREATE TABLE student
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(32) DEFAULT NULL,
phone
varchar(11) DEFAULT NULL,
sex
int(1) DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1. 批量新增
首先我们要知道批量新增的sql语句怎么来写,以mysql为例,批量新增的sql语句语法如下:
insert into tablename (col1, col2, col3) values (v1, v2, v3), (v4, v5, v6),....
那么体现在mybatis的mapper文件中具体应该怎么写呢,其实就是要用到foreach标签,使用循环的方式来生成 value后面的那段内容,具体代码如下:
接口中声明的方法(传入参数是一个list对象):
int batchInsert(List<Student> students);
mapper文件中对应标签如下:
<insert id="batchInsert">
insert into student (name, phone, sex)
values
<!--
collection 要遍历的集合类型或者对象名称
separator 两次遍历中间的分隔符
item 遍历过程中取出的元素对象名称
遍历后最终生成的sql语句是:
insert into student (name, phone, sex)
values (?, ?, ?), (?, ?, ?), (?, ?, ?), ...
-->
<foreach collection="list" separator="," item="student">
(#{student.name}, #{student.phone}, #{student.sex})
</foreach>
</insert>
2. 批量删除
批量删除的sql语句语法如下:
delete from tablename where id in (?, ?, ?, ?,...)
那么体现在mybatis的mapper文件中也是要用到foreach标签,使用循环的方式来生成 in后面的那段内容,具体代码如下:
接口中声明的方法(传入参数是一个数组对象):
int batchDelete(int[] ids);
mapper文件中对应标签如下:
<delete id="batchDelete">
delete from student where id in
<!--
collection 要遍历的集合类型或者对象名称
separator 两次遍历中间的分隔符
item 遍历过程中取出的元素对象名称
open 添加在 foreach完生成的内容的前缀内容
close 添加在 foreach完生成的内容的后缀内容
遍历后最终生成的sql语句是:
delete from student in (?, ?, ?, ...)
-->
<foreach collection="array" open="(" close=")" separator="," item="id">
#{id}
</foreach>
</delete>
3. 批量修改
批量修改的sql语句语法如下:
update tablename set
col1 = case when id = id1 then v11 when id = id2 then v12 ... end,
col2 = case when id = id1 then v21 when id = id2 then v22 ... end,
...
where id in
(id1, id2, ...)
那么体现在mybatis的mapper文件中也是要用到foreach标签,使用循环的方式来生成when … then … 以及where … in这部分内容,具体代码如下:
接口中声明的方法(传入参数是一个list对象):
int batchUpdate(List<Student> students);
mapper文件中对应标签如下:
<update id="batchUpdate">
update student
set name =
<foreach collection="list" open="case" close="end" item="student">
when id = #{student.id} then #{student.name}
</foreach>
, phone =
<foreach collection="list" open="case" close="end" item="student">
when id = #{student.id} then #{student.phone}
</foreach>
, sex =
<foreach collection="list" open="case" close="end" item="student">
when id = #{student.id} then #{student.sex}
</foreach>
where id in
<foreach collection="list" open="(" close=")" separator="," item="student">
#{student.id}
</foreach>
</update>
注意事项:
**因为mysql的sql语句是有长度限制的,可以在mysql的客户端执行以下语句查看具体长度:
show variables where variable_name like 'max_allowed_packet';
所以大批量的数据进行新增时,还是要分段去批量操作,比如拆分成每1万条记录批量新增一次。**
附上源码链接
mybatis批量新增删除和修改源码