zoukankan      html  css  js  c++  java
  • MybatisPlus批量保存源码分析

    IService介绍接口

    使用MybatisPlus代码生成器自动生成IUserService接口并继承IService

    查看IService接口已经封装了诸多方法

    并由ServiceImpl继承并实现

    public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
        
    }
    

    image-20200804100651593

    IService接口

    /**
     * 获取 SqlStatement
     *
     * @param sqlMethod ignore
     * @return ignore
     */
    protected String sqlStatement(SqlMethod sqlMethod) {
        return SqlHelper.table(entityClass).getSqlStatement(sqlMethod.getMethod());
    }
    
    @Override
    public boolean saveBatch(Collection<User> entityList, int batchSize) {
        // 获取insert插入语句:INSERT INTO xxx VALUES xxx
        String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
        
        // 执行批量删除操作
        // 参数一:entity集合
        // 参数二:执行次数
        // 参数三 : 接收两个参数的函数接口并执行 sqlSession.insert(sqlStatement,user)方法
        return executeBatch(entityList, batchSize,
                            (sqlSession, user) -> sqlSession.insert(sqlStatement,user));
    }
    

    ServiceImpl实现类

    /**
     * 执行批量操作
     *
     * @param list      数据集合
     * @param batchSize 批量大小
     * @param consumer  执行方法
     * @param <E>       泛型
     * @return 操作结果
     * @since 3.3.1
     */
    protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
        Assert.isFalse(batchSize < 1, "batchSize must not be less than one");
        return !CollectionUtils.isEmpty(list) && executeBatch(sqlSession -> {
            int size = list.size();
            int i = 1;
            for (E element : list) {
                
                // comsumer 对象引用函数(sqlSession, user)
                // 调用方法 accept 接收参数 SqlSession 和 User对象的引用
                // 然后执行 sqlSession.insert(sqlStatement,user) 方法
                consumer.accept(sqlSession, element);
                
                if ((i % batchSize == 0) || i == size) {
                    // 刷新批处理语句:最终执行 insert 插入语句
                    sqlSession.flushStatements();
                }
                i++;
            }
        });
    }
    
  • 相关阅读:
    日志记录到txt文件
    使用NuGet安装EntityFramework4.2
    Redis 安装与简单示例 <第一篇>
    时间加减时间段(年、月、日、分、秒)
    控件属性设置
    window.showModalDialog 与window.open传递参数的不同?
    如何进行js动态生成option?如何实现二级连动?
    System.Data.SqlClient.SqlError: 备份集中的数据库备份与现有的 'XXX' 数据库不同
    如何激发手机的高分辨率
    PHP--正则表达式和样式匹配--小记
  • 原文地址:https://www.cnblogs.com/code-duck/p/13432065.html
Copyright © 2011-2022 走看看