mybatis-plus 批量插入示例

打印 上一主题 下一主题

主题 992|帖子 992|积分 2976

正常我们使用mybatis-plus插入的时候,首先想到的是  saveBatch 方法,不过看了下打印出来的sql和底层代码,才发现它并不是真正的批量插入。
  1. IService 中的代码为
复制代码
  1.     default boolean saveBatch(Collection<T> entityList) {
  2.         return this.saveBatch(entityList, 1000);
  3.     }
复制代码
    实现层   ServiceImpl 中的代码为
  1.     public boolean saveBatch(Collection<T> entityList, int batchSize) {
  2.         String sqlStatement = this.getSqlStatement(SqlMethod.INSERT_ONE);
  3.         return this.executeBatch(entityList, batchSize, (sqlSession, entity) -> {
  4.             sqlSession.insert(sqlStatement, entity);
  5.         });
  6.     }
复制代码
  1. SqlMethod.INSERT_ONE 的中文枚举为  <br>
复制代码
  1. INSERT_ONE("insert", "插入一条数据(选择字段插入)", ""),
复制代码
通过监控控制台发现,它只是循环每1000条去插入,效率非常低。
 
参考网友的文章,找到一个支持批量操作的方法,下面直接贴上代码
1、添加批量操作参数类  CustomSqlInjector
  1. /**
  2. * 支持自定义SQL注入方法
  3. */
  4. public class CustomSqlInjector extends DefaultSqlInjector {
  5.     @Override
  6.     public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
  7.         // 获取父类SQL注入方法列表
  8.         List<AbstractMethod> methodList = super.getMethodList(mapperClass);
  9.         // 将批量插入方法添加进去
  10.         methodList.add(new InsertBatchSomeColumn());
  11.         return methodList;
  12.     }
  13. }
复制代码
2、在MybatisPlusConfig中配置 
  1. @Bean
  2. public CustomSqlInjector customSqlInjector() {
  3.      return new CustomSqlInjector();
  4. }
复制代码
3、添加自定义 Mapper接口 
  1. /**
  2. * 自定义Mapper,添加批量插入接口
  3. * @param <T>
  4. */
  5. @Mapper
  6. public interface CustomMapper<T> extends BaseMapper<T> {
  7.     /**
  8.      * 批量插入
  9.      * @param entityList 实体列表
  10.      * @return 影响行数
  11.      */
  12.     Integer insertBatchSomeColumn(Collection<T> entityList);
  13. }
复制代码
4、将原来的Mapper业务接口,换成继承此接口
  1. @Mapper
  2. public interface StudentDao extends CustomMapper<Student> {
  3.     List<Student> query(Student student);
  4. }
复制代码
5、再进行测试一下
[code]    @Transactional  //事务注解要加上    @Override    public void testBatchCreate() {        List list = new ArrayList();        int startIndex = this.lambdaQuery().select(Student::getId).count();        for (int i = 1; i
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

笑看天下无敌手

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表