TestBatchController.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.AjaxResult;
  5. import com.ruoyi.demo.domain.TestDemo;
  6. import com.ruoyi.demo.service.ITestDemoService;
  7. import io.swagger.annotations.Api;
  8. import io.swagger.annotations.ApiOperation;
  9. import lombok.RequiredArgsConstructor;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.web.bind.annotation.DeleteMapping;
  12. import org.springframework.web.bind.annotation.PostMapping;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RestController;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17. /**
  18. * 测试批量方法
  19. *
  20. * @author Lion Li
  21. * @date 2021-05-30
  22. */
  23. @Api(value = "测试批量方法", tags = {"测试批量方法"})
  24. @RequiredArgsConstructor(onConstructor_ = @Autowired)
  25. @RestController
  26. @RequestMapping("/demo/batch")
  27. public class TestBatchController extends BaseController {
  28. private final ITestDemoService iTestDemoService;
  29. /**
  30. * 新增批量方法 可完美替代 saveBatch 秒级插入上万数据 (对mysql负荷较大)
  31. */
  32. @ApiOperation(value = "新增批量方法")
  33. @PostMapping("/add")
  34. // @DS("slave")
  35. public AjaxResult<Void> add() {
  36. List<TestDemo> list = new ArrayList<>();
  37. for (int i = 0; i < 1000; i++) {
  38. list.add(new TestDemo().setOrderNum(-1L).setTestKey("批量新增").setValue("测试新增"));
  39. }
  40. return toAjax(iTestDemoService.saveAll(list) ? 1 : 0);
  41. }
  42. /**
  43. * 新增或更新 可完美替代 saveOrUpdateBatch 高性能
  44. */
  45. @ApiOperation(value = "新增或更新批量方法")
  46. @PostMapping("/addOrUpdate")
  47. // @DS("slave")
  48. public AjaxResult<Void> addOrUpdate() {
  49. List<TestDemo> list = new ArrayList<>();
  50. for (int i = 0; i < 1000; i++) {
  51. list.add(new TestDemo().setOrderNum(-1L).setTestKey("批量新增").setValue("测试新增"));
  52. }
  53. iTestDemoService.saveAll(list);
  54. for (int i = 0; i < list.size(); i++) {
  55. TestDemo testDemo = list.get(i);
  56. testDemo.setTestKey("批量新增或修改").setValue("批量新增或修改");
  57. if (i % 2 == 0) {
  58. testDemo.setId(null);
  59. }
  60. }
  61. return toAjax(iTestDemoService.saveOrUpdateAll(list) ? 1 : 0);
  62. }
  63. /**
  64. * 删除批量方法
  65. */
  66. @ApiOperation(value = "删除批量方法")
  67. @DeleteMapping()
  68. // @DS("slave")
  69. public AjaxResult<Void> remove() {
  70. return toAjax(iTestDemoService.remove(new LambdaQueryWrapper<TestDemo>()
  71. .eq(TestDemo::getOrderNum, -1L)) ? 1 : 0);
  72. }
  73. }