//业务背景:在实现一次性插入上万条数据时会报错,所有要批量插入
public void addCouponCode(List<CouponCodeEntity> lists){ if (CollectionUtils.isEmpty(lists)) { return; } int numPerTimes = 200; if (lists.size() <= numPerTimes) { batchAdd(lists); //直接插入少于200条lists } else { int maxIndex = lists.size(); int maxTimes = maxIndex / numPerTimes; maxTimes += (maxIndex % numPerTimes) > 0 ? 1 : 0; int currentTimes = 0; while (currentTimes < maxTimes) { int fromIndex = numPerTimes * currentTimes; int toIndex = fromIndex + numPerTimes; toIndex = toIndex > maxIndex ? maxIndex : toIndex; List<CouponCodeEntity> subList = lists.subList(fromIndex, toIndex); batchAdd(subList); //循环插入200条lists currentTimes++; } } }
public void batchAdd(List<CouponCodeEntity> lists) { if (CollectionUtils.isEmpty(lists)) throw new BizException(-1, "lists为空"); //空值抛出异常 couponCodeEntityMapper.batchInsert(lists); //mybatis插入,可根据业务自行修改 }
//缺点:传入的lists较大,可考虑分页查询再插入