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
entityList); / *
* 插入(批量) *
* * @param entityList 实体对象列表 * @param batchSize 插入批次数量 * @return boolean */ boolean insertBatch(List
entityList, int batchSize);
使用方法,定义一个自己的接口,继承IService,泛型为被操作实体类
@Service public interface WorkIService extends IService
{ }
定义一个实现类,实现上诉接口
@Service public class WorkIServiceImpl extends ServiceImpl
implements WorkIService{ }
其中WorkMapper为正常操作的mapper
在业务中测试批量插入操作
List
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; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217680.html原文链接:https://javaforall.net
