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++;
            }
        });
    }
    
  • 相关阅读:
    springmvc
    POJ 3683 Priest John's Busiest Day
    POJ 3678 Katu Puzzle
    HDU 1815 Building roads
    CDOJ UESTC 1220 The Battle of Guandu
    HDU 3715 Go Deeper
    HDU 3622 Bomb Game
    POJ 3207 Ikki's Story IV
    POJ 3648 Wedding
    HDU 1814 Peaceful Commission
  • 原文地址:https://www.cnblogs.com/code-duck/p/13432065.html
Copyright © 2011-2022 走看看