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++;
        }
    });
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM