目标:

  1. mybatis-plus批处理的原理和过程
  2. 验证的技术方案
  3. 性能评估方案
  4. 最佳实践(应用规范)

    1. 批处理的核心逻辑

    com.baomidou.mybatisplus.core.executor.MybatisBatchExecutor#doFlushStatements
    1. @Override
    2. public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {
    3. try {
    4. List<BatchResult> results = new ArrayList<>();
    5. if (isRollback) {
    6. return Collections.emptyList();
    7. }
    8. for (int i = 0, n = statementList.size(); i < n; i++) {
    9. Statement stmt = statementList.get(i);
    10. applyTransactionTimeout(stmt);
    11. BatchResult batchResult = batchResultList.get(i);
    12. try {
    13. batchResult.setUpdateCounts(stmt.executeBatch());
    14. MappedStatement ms = batchResult.getMappedStatement();
    15. List<Object> parameterObjects = batchResult.getParameterObjects();
    16. KeyGenerator keyGenerator = ms.getKeyGenerator();
    17. if (Jdbc3KeyGenerator.class.equals(keyGenerator.getClass())) {
    18. Jdbc3KeyGenerator jdbc3KeyGenerator = (Jdbc3KeyGenerator) keyGenerator;
    19. jdbc3KeyGenerator.processBatch(ms, stmt, parameterObjects);
    20. } else if (!NoKeyGenerator.class.equals(keyGenerator.getClass())) { //issue #141
    21. for (Object parameter : parameterObjects) {
    22. keyGenerator.processAfter(this, ms, stmt, parameter);
    23. }
    24. }
    25. // Close statement to close cursor #1109
    26. closeStatement(stmt);
    27. } catch (BatchUpdateException e) {
    28. StringBuilder message = new StringBuilder();
    29. message.append(batchResult.getMappedStatement().getId())
    30. .append(" (batch index #")
    31. .append(i + 1)
    32. .append(")")
    33. .append(" failed.");
    34. if (i > 0) {
    35. message.append(" ")
    36. .append(i)
    37. .append(" prior sub executor(s) completed successfully, but will be rolled back.");
    38. }
    39. throw new BatchExecutorException(message.toString(), e, results, batchResult);
    40. }
    41. results.add(batchResult);
    42. }
    43. return results;
    44. } finally {
    45. for (Statement stmt : statementList) {
    46. closeStatement(stmt);
    47. }
    48. currentSql = null;
    49. statementList.clear();
    50. batchResultList.clear();
    51. }
    52. }