本文以批量插入配置爲例,其他半斤八兩~
Spring boot+mybatis plus環境,單條插入用的是BaseMapper自帶的insert方法
public ApiResult addAnc(Anc anc) {
ApiResult result = new ApiResult();
Integer insert = ancMapper.insert(anc);
if (insert < 1) {
return result.failed("發佈失敗,請聯繫管理員");
}
return result.success(anc);
}
BaseMapper未提供批量插入接口,但是在com.baomidou.mybatisplus.service.IService中提供了
/**
* 插入(批量),該方法不適合 Oracle
*
* @param entityList 實體對象列表
* @return boolean
*/
boolean insertBatch(List<T> entityList);
/**
* 插入(批量)
*
* @param entityList 實體對象列表
* @param batchSize 插入批次數量
* @return boolean
*/
boolean insertBatch(List<T> entityList, int batchSize);
使用方法,定義一個自己的接口,繼承IService,泛型爲被操作實體類
public interface WorkIService extends IService<CmpWork> {
}
其中WorkMapper爲正常操作的mapper,在業務中測試批量插入操作
List<CmpWork> entityList = new ArrayList<>(1000);
for (int i=1;i<10000;i++){
CmpWork work = new CmpWork();
work.setWorkName("workNametestBatch"+i);
work.setWorkID("testBatch"+i);
work.setCreTm(DateUtil.dateToYMDHMS(new Date()));
entityList.add(work);
}
boolean b = workIService.insertBatch(entityList);
和單條插入的執行對比了一下,在1000條數據級別內,差別不大,批量操作的優勢可能大數據環境下才能顯現吧!