MyBatis笔记(三):MyBatis 针对大批量数据分批提交更新

在使用 Mybatis 进行数据批量新增的时候,有时候数据过大时需要进行分批处理。这个时候就需要一些特殊的处理了。

以下代码,博主未做测试,此处仅用来收藏,方便以后使用。

 public void saveTemp(List<AddressBookDepartmentAllSyncTemp> allSyncTemps) {
	if (allSyncTemps.size() <= batchUpdateSize) {
		baseMapper.insertBatch(allSyncTemps);
	} else {
		SqlSession sqlSession = null;
		try {
			sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
			List<AddressBookDepartmentAllSyncTemp> temps = new ArrayList<>();

			for (int index = 0,len = allSyncTemps.size() ; index < len; index ++) {
				if(!ObjectUtils.isEmpty(allSyncTemps.get(index))){
					temps.add(allSyncTemps.get(index));
				}
				if(index != 0 && index % batchUpdateSize == 0 && !ObjectUtils.isEmpty(temps)){
					baseMapper.insertBatch(temps);
					sqlSession.commit();
					temps.clear();
				}else if(index == len-1 && !ObjectUtils.isEmpty(temps)){
					baseMapper.insertBatch(temps);
					sqlSession.commit();
					temps.clear();
				}
			}
		}catch (Exception e){
			sqlSession.rollback();
			throw new RuntimeException("保存部门临时数据异常",e);
		}finally {
			if (sqlSession != null) {
				sqlSession.close();
			}

		}}
	}
}

baseMapper.java

void insertBatch(List<AddressBookDepartmentAllSyncTemp> list);

Mapper.xml

<insert id="insertBatch" >
	insert into address_book_department_all_sync_temp (`id`,`data`) values
	<foreach collection="list" item="item" index="index" separator=",">
		(#{item.id},#{item.data})
	</foreach>
</insert>

文末附:MyBatis笔记(四):JDBC对大数据量的批量执行Demo

以上案例如果仍然无法满足大数据量的执行(插入、更新)操作。建议你修改一下 MySQL 数据库批处理 SQL 拼接允许的最大值。默认是 4M,此值可以自行修改的,你可以自行百度一下。


End

发布了301 篇原创文章 · 获赞 66 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/lzb348110175/article/details/104576721