在使用mybatis进行数据批量新增的时候,有时候数据过大时需要进行分批处理。这个时候就需要一些特殊的处理了,不多说,直接上代码
public void saveTemp(List<AddressBookDepartmentAllSyncTemp> allSyncTemps) {
baseMapper.deleteTempTable();
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();
}
}}
}
mapp.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>