TestBatchController.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package com.ruoyi.demo.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.ruoyi.common.core.controller.BaseController;
  4. import com.ruoyi.common.core.domain.R;
  5. import com.ruoyi.demo.domain.TestDemo;
  6. import com.ruoyi.demo.mapper.TestDemoMapper;
  7. import lombok.RequiredArgsConstructor;
  8. import org.springframework.web.bind.annotation.DeleteMapping;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. /**
  15. * 测试批量方法
  16. *
  17. * @author Lion Li
  18. * @date 2021-05-30
  19. */
  20. @RequiredArgsConstructor
  21. @RestController
  22. @RequestMapping("/demo/batch")
  23. public class TestBatchController extends BaseController {
  24. /**
  25. * 为了便于测试 直接引入mapper
  26. */
  27. private final TestDemoMapper testDemoMapper;
  28. /**
  29. * 新增批量方法 可完美替代 saveBatch 秒级插入上万数据 (对mysql负荷较大)
  30. * <p>
  31. * 3.5.0 版本 增加 rewriteBatchedStatements=true 批处理参数 使 MP 原生批处理可以达到同样的速度
  32. */
  33. @PostMapping("/add")
  34. // @DS("slave")
  35. public R<Void> add() {
  36. List<TestDemo> list = new ArrayList<>();
  37. for (int i = 0; i < 1000; i++) {
  38. TestDemo testDemo = new TestDemo();
  39. testDemo.setOrderNum(-1);
  40. testDemo.setTestKey("批量新增");
  41. testDemo.setValue("测试新增");
  42. list.add(testDemo);
  43. }
  44. return toAjax(testDemoMapper.insertBatch(list) ? 1 : 0);
  45. }
  46. /**
  47. * 新增或更新 可完美替代 saveOrUpdateBatch 高性能
  48. * <p>
  49. * 3.5.0 版本 增加 rewriteBatchedStatements=true 批处理参数 使 MP 原生批处理可以达到同样的速度
  50. */
  51. @PostMapping("/addOrUpdate")
  52. // @DS("slave")
  53. public R<Void> addOrUpdate() {
  54. List<TestDemo> list = new ArrayList<>();
  55. for (int i = 0; i < 1000; i++) {
  56. TestDemo testDemo = new TestDemo();
  57. testDemo.setOrderNum(-1);
  58. testDemo.setTestKey("批量新增");
  59. testDemo.setValue("测试新增");
  60. list.add(testDemo);
  61. }
  62. testDemoMapper.insertBatch(list);
  63. for (int i = 0; i < list.size(); i++) {
  64. TestDemo testDemo = list.get(i);
  65. testDemo.setTestKey("批量新增或修改");
  66. testDemo.setValue("批量新增或修改");
  67. if (i % 2 == 0) {
  68. testDemo.setId(null);
  69. }
  70. }
  71. return toAjax(testDemoMapper.insertOrUpdateBatch(list) ? 1 : 0);
  72. }
  73. /**
  74. * 删除批量方法
  75. */
  76. @DeleteMapping()
  77. // @DS("slave")
  78. public R<Void> remove() {
  79. return toAjax(testDemoMapper.delete(new LambdaQueryWrapper<TestDemo>()
  80. .eq(TestDemo::getOrderNum, -1L)));
  81. }
  82. }