0
点赞
收藏
分享

微信扫一扫

MyBatis-Plus 批量插入

晚安大世界 2022-03-21 阅读 95
java后端

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中提供了

    /**
     * <p>
     * 插入(批量),该方法不适合 Oracle
     * </p>
     *
     * @param entityList 实体对象列表
     * @return boolean
     */
    boolean insertBatch(List<T> entityList);

    /**
     * <p>
     * 插入(批量)
     * </p>
     *
     * @param entityList 实体对象列表
     * @param batchSize  插入批次数量
     * @return boolean
     */
    boolean insertBatch(List<T> entityList, int batchSize);

使用方法,定义一个自己的接口,继承IService,泛型为被操作实体类

@Service
public  interface  WorkIService extends IService<CmpWork> {

}

定义一个实现类,实现上诉接口

@Service
public class WorkIServiceImpl extends ServiceImpl<WorkMapper, CmpWork> implements WorkIService{
}

其中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条数据级别内,差别不大

经探究,其实其内部实现用的就是for循环,搞了个寂寞~

@Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertBatch(List<T> entityList, int batchSize) {
        if (CollectionUtils.isEmpty(entityList)) {
            throw new IllegalArgumentException("Error: entityList must not be empty");
        }
        try (SqlSession batchSqlSession = sqlSessionBatch()) {
            int size = entityList.size();
            String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
            for (int i = 0; i < size; i++) {
                batchSqlSession.insert(sqlStatement, entityList.get(i));
                if (i >= 1 && i % batchSize == 0) {
                    batchSqlSession.flushStatements();
                }
            }
            batchSqlSession.flushStatements();
        } catch (Throwable e) {
            throw new MybatisPlusException("Error: Cannot execute insertBatch Method. Cause", e);
        }
        return true;
    }
举报

相关推荐

0 条评论