mybatis mysql数据库批量操作
在我们写代码的时候经常会进行一些批量操作,不经常写的话会忘记。在此仅记录一下常用的sql代码。
1. 批量新增
Mapper文件
int batchInsert(List<NoticeDetail> list);
Mapper.xml文件
<insert id="batchInsert">
INSERT INTO notice_scope_detail (notice_id, obj_id)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.noticeId}, #{item.objId})
</foreach>
</insert>
2. 批量新增并更新
数据量太大的时候不能一下子全部更新,要分批次进行操作。
java代码
List<MigrateEtcHandoverLogKey> list = mysqlMigrateTableDaoService.selectHandoverList(dto.getBranchNo());
if (list == null || list.isEmpty()) {
return BeeResponseEntity.success();
}
// 分批次插入,每次100条
int batchSize = Math.min(list.size(), 100);
for (int i = 0; i < list.size(); i += batchSize) {
int endIndex = Math.min(list.size(), i + batchSize);
List<MigrateEtcHandoverLogKey> batchList = list.subList(i, endIndex);
//
oracleMigrateTableDaoService.batchInsertOrUpdate(batchList);
}
return BeeResponseEntity.success();
Mapper文件
int batchInsertOrUpdate(List<NoticeDetail> list);
Mapper.xml文件
方法一:DUPLICATE KEY
<insert id="batchInsertOrUpdate">
INSERT INTO notice_scope_detail (notice_id, obj_id)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.noticeId}, #{item.objId})
</foreach>
ON DUPLICATE KEY UPDATE
notice_id = VALUES(notice_id),
obj_id = VALUES(obj_id);
</insert>
方法二: replace into
<insert id="batchInsertOrUpdate">
replace into notice_scope_detail (notice_id, obj_id)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.noticeId}, #{item.objId})
</foreach>
</insert>
3.批量更新
Mapper文件
int updateBatch(List<NoticeDetail> list);
Mapper.xml文件
<update id="updateBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update tableName
<set>
name=${item.name},
name2=${item.name2}
</set>
where id = ${item.id}
</foreach>
</update>
Mybatis映射文件中的sql语句默认是不支持以" ; " 结尾的,也就是不支持多条sql语句的执行。所以需要在连接mysql的url上加 &allowMultiQueries=true 这个才可以执行。