Mybatis-Plus批量新增
生活随笔
收集整理的這篇文章主要介紹了
Mybatis-Plus批量新增
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景:提供的insertBatch是假批量,重復的IO連接與斷開效率極低,提供了insertBatchSomeColumn真批量需要自己手動配置
直接上代碼:
public interface MyMapper<T> extends BaseMapper<T> {/*** 默認批次提交數量*/int DEFAULT_BATCH_SIZE = 1000;/*** 批量新增數據,自選字段 insert. 自動按每批1000插入數據庫* 此填充不會填充 FieldFill.UPDATE 的字段。* 注意數據庫默認更新的字段也需要手工設置** @param entityList 數據* @return 插入條數*/@Transactional(rollbackFor = Exception.class)default int insertBatch(List<T> entityList) {return this.insertBatchSomeColumn(entityList, DEFAULT_BATCH_SIZE);}/*** 批量新增數據,自選字段 insert* 不會分批插入,需要分批請調用方法insertBatch或者 insertBatchSomeColumn(List<T> entityList, int size)* 此填充不會填充 FieldFill.UPDATE 的字段。* 注意數據庫默認更新的字段也需要手工設置** @param entityList 數據* @return 插入條數*/int insertBatchSomeColumn(List<T> entityList);/*** 分批插入。每次插入* @param entityList 原實體對象* @param size 分批大小* @return 總插入記錄*/@Transactional(rollbackFor = Exception.class)default int insertBatchSomeColumn(List<T> entityList, int size) {if (CollUtil.isEmpty(entityList)) {return 0;}List<List<T>> split = CollUtil.split(entityList, size);return split.stream().mapToInt(this::insertBatchSomeColumn).sum();} }有使用工具類,可以引入以下依賴
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.3</version> </dependency>以下的操作也需要,要不可能會有其他bug:
public class MySqlInjector extends DefaultSqlInjector {@Overridepublic List<AbstractMethod> getMethodList(Class<?> mapperClass) {List<AbstractMethod> methodList = super.getMethodList(mapperClass);// 例: 不要指定了 update 填充的字段methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));return methodList;} } @Configuration public class MybatisPlusConfig {/*** 自定義內置選裝件* @return*/@Beanpublic MySqlInjector sqlInjector() {return new MySqlInjector();} }總結
以上是生活随笔為你收集整理的Mybatis-Plus批量新增的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 智印致in 兄弟按需供粉系列打印机新品发
- 下一篇: 前端机器学习——线性回归