MyBatis批处理
MyBatis批量处理本质
减少了网络传输开销原因?
减少无谓的请求头,如果你每个请求只有几字节,而头却有几十字节,无疑效率非常低下。
减少回复的ack包个数。把请求合并后,ack包数量必然减少,确认和重发的成本就会降低。
注意事项:
1. 使用批处理要注意分片大小,不易过大
2. 在使用mybatis内置executeBatch批处理,本质上也就是jdbc的批处理。jdbc连接参数要添加rewriteBatchedStatements=true批处理才会生效
其本身是将sql语句添加到一个集合中,一块发送给mysql服务器
3. jdbc原生相比于Mybatis批处理效率更高
4. 使用sql拼接则不用开启rewriteBatchedStatements,需要设置allowMultiQueries=true,允许更新、修改时候多条sql可以用;分开一起提交到服务器中
5. 【executeBatch批处理】与【手写拼接的sql】 两者都是将多条sql语句打包一块通过网络请求实现的,只不过前者是jdbc内置api实现而已
手写拼接的sql批处理
批量新增
<insert id="insertBatch">
INSERT INTO `tb_user_info`(`login_account`, `password`, `username`, `dept_id`, `data_status`, `create_by`,
`create_time`,
`update_by`, `update_time`, `record_version`, `update_count`)
VALUES
<foreach collection="entities" item="entity" separator=",">
(#{entity.loginAccount},
#{entity.password},
#{entity.username},
#{entity.deptId},
#{entity.dataStatus},
#{entity.createBy},
#{entity.createTime},
#{entity.updateBy},
#{entity.updateTime},
#{entity.recordVersion},
#{entity.updateCount})
</foreach>
</insert>
批量修改
<update id="updateBatchById">
<foreach collection="list" item="s" separator=";">
update
`t_student`
set
`name` = #{name},
`age` = #{age}
where
id = #{id}
</foreach>
</update>
注意:我们需要通过在数据库连接URL中指定allowMultiQueries参数值为true告诉数据库以支持";"号分隔的多条语句一块的执行,否则会报错
批量删除
使用foreach标签同批量修改、in操作都可以
案例日志
删除
batchDelete(10条记录) => 发送一次请求,内容为”delete from t where id = 1; delete from t where id = 2; delete from t where id = 3; ….”
或者
delete from t where id in(1,2,3,4,5,....n)
更新
batchUpdate(10条记录) => 发送一次请求,内容为”update t set … where id = 1; update t set … where id = 2; update t set … where id = 3 …”
新增
batchInsert(10条记录) => 发送一次请求,内容为”insert into t (…) values (…) , (…), (…)”
对delete和update,驱动所做的事就是把多条sql语句累积起来再一次性发出去;而对于insert,驱动则会把多条sql语句重写成一条sql语句,然后再发出去。
rewriteBatchedStatements与allowMultiQueries区别
1. rewriteBatchedStatements是重写sql语句达到发送一次sql的请求效果,是针对PreparedStatement#executeBatch()方法,而Mybatis的自带的批处理方法本质上就是这个,如果不开启rewriteBatchedStatements=true,还是会一条一条插入。开启后会变成:insert into t (…) values (…) , (…), (…),执行一次就可以处理
2. allowMultiQueries是针对于在xml的mapper中使用分号多个sql一块发送执行的,针对与**update,delete**,,默认不允许使用分号有多个sql语句一块执行的。
参考
Mybatis之批量更新数据(批量update) - 知乎 (zhihu.com)
MySQL Jdbc驱动的rewriteBatchedStatements参数 关于批处理_mysql中的rewritebatchedsta_来个地瓜的博客-CSDN博客

浙公网安备 33010602011771号