2.创建数据库和表
此步骤可省略,主要用于本文功能的实现,创建数据库和数据表的脚本如下:
-- ---------------------------- -- 创建数据库 -- ---------------------------- SETNAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; DROPDATABASEIFEXISTS`testdb`; CREATEDATABASE`testdb`; USE`testdb`; -- ---------------------------- -- 创建 user 表 -- ---------------------------- DROPTABLEIFEXISTS`user`; CREATETABLE`user` ( `id`int(11) NOTNULL AUTO_INCREMENT, `name`varchar(255) CHARACTERSET utf8mb4 COLLATE utf8mb4_bin NULLDEFAULTNULL, `password`varchar(255) CHARACTERSET utf8mb4 COLLATE utf8mb4_bin NULLDEFAULTNULL, `createtime` datetime NULLDEFAULTCURRENT_TIMESTAMP, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 6CHARACTERSET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; -- ---------------------------- -- 添加测试数据 -- ---------------------------- INSERTINTO`user`VALUES (1, '赵云', '123456', '2021-09-10 18:11:16'); INSERTINTO`user`VALUES (2, '张飞', '123456', '2021-09-10 18:11:28'); INSERTINTO`user`VALUES (3, '关羽', '123456', '2021-09-10 18:11:34'); INSERTINTO`user`VALUES (4, '刘备', '123456', '2021-09-10 18:11:41'); INSERTINTO`user`VALUES (5, '曹操', '123456', '2021-09-10 18:12:02'); SET FOREIGN_KEY_CHECKS = 1;
3.具体代码实现(重点)
① 实体类
先来创建数据库所对应的 User 实体类:
import lombok.Getter; import lombok.Setter; import java.util.Date; @Getter @Setter publicclass User { privateint id; private String name; private String password; private Date createtime; }
② Controller 层代码
本文的核心是使用 MP 框架中,IService 类提供的 saveBatch 方法,来实现批量数据的插入功能,对应在 Controller 中的实现代码如下:
import com.example.demo.model.User; import com.example.demo.service.impl.UserServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/u") publicclass UserController { @Autowired private UserServiceImpl userService; /** * MP 批量插入 */ @RequestMapping("/savebatch") public boolean saveBatch() { List<User> list = new ArrayList<>(); // 待添加(用户)数据 for (int i = 0; i < 1000; i++) { User user = new User(); user.setName("test:"+i); user.setPassword("123456"); list.add(user); } // 批量插入 return userService.saveBatch(list); } }