MyBatis-Plus - 批量插入、更新、删除、查询

本文以批量插入配置为例,其他半斤八两~

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条数据级别内,差别不大,批量操作的优势可能大数据环境下才能显现吧!

猜你喜欢

转载自blog.csdn.net/Dream_Weave/article/details/106800198