作者|王磊来源|Java中文社区(ID:javacn666)请联系授权(微信ID:GG_Stone)最近在查看小伙伴的代码时,发现一个小问题,小伙伴居然在for循环中执行了插入(insert)的操作)写入数据库会导致每次循环都要进行连接、插入、断开等操作,会导致一定的性能问题。简化代码如下:/***插入操作*/@RequestMapping("/save")publicObjectsave(){booleanflag=false;//返回结果//待添加(用户)数据for(inti=0;i<1000;i++){Useruser=newUser();user.setName("test:"+i);user.setPassword("123456");//插入数据影响程序的执行效率。比如你要从A点发10件货物到B点,你可以选择一次发1件,发10次的方案;你也可以选择一次发10件和发1次的方案,你会选择哪个?这就是多次循环插入和批量一次性插入的问题。PS:插入的数据量越大,批量插入的时间(相对于循环多次插入而言)越短,其优势越大。批量插入实现本文使用MyBatis-Plus(以下简称MP)自带的saveBatch方法来实现数据的批量插入功能,因为MP不是本文讨论的重点,所以我们先不说'这里就不介绍了。如果有不熟悉的朋友可以去他的官网看看:https://baomidou.com/guide/。本文重点介绍MP批量插入的具体实现。步。1.引入MP框架首先,打开你的pom.xml文件,在文件中添加如下内容:com.baomidoumybatis-plus-boot-startermybatis-plus-latest-version注:mybatis-plus-latest-version表示MP框架的最新版本号,可访问https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter查询最新的版本号,但是使用的时候记得把上面的“mybatis-plus-latest-version”替换成具体的版本号,比如3.4.3为正常引入框架。2.创建数据库和表这一步可以省略,主要是为了实现本文的功能,创建数据库和数据表的脚本如下:------------------------------创建数据库------------------------------SETNAMESutf8mb4;SETFOREIGN_KEY_CHECKS=0;DROPDATABASEIFEXISTS`testdb`;CREATEDATABASE`testdb`;USE`testdb`;------------------------------创建用户表------------------------------DROPTABLEIFEXISTS`user`;CREATETABLE`user`(`id`int(11)NOTNULLAUTO_INCREMENT,`name`varchar(255)CHARACTERSETutf8mb4COLLATEutf8mb4_binNULLDEFAULTNULL,`password`varchar(255)CHARACTERSETutf8mb4COLLATEutf8mb4_binNULLDEFAULTNULL,`createtime`datetimeNULLDEFAULTCURRENT_TIMESTAMP,PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBAUTO_INCREMENT=6CHARACTERSET=utf8mb4COLLATE=utf8mb4_binROW_FORMAT=Dynamic;-------------------------------添加测试数据----------------------------INSERTINTO`user`VALUES(1,'赵云','123456','2021-09-1018:11:16');INSERTINTO`user`VALUES(2,'张Fei','123456','2021-09-1018:11:28');INSERTINTO`user`VALUES(3,'关羽','123456','2021-09-1018:11:34');INSERTINTO`user`VALUES(4,'刘备','123456','2021-09-1018:11:41');INSERTINTO`user`VALUES(5,'曹操','123456','2021-09-1018:12:02');SETFOREIGN_KEY_CHECKS=1;3.具体代码实现(重点)①实体类首先创建数据库对应的User实体类:importlombok.Getter;importlombok.Setter;importjava.util.Date;@Getter@SetterpublicclassUser{privateintid;privateStringname;privateStringpassword;privateDatecreatetime;}②Controller层代码文章的核心是利用MP框架中IService类提供的saveBatch方法实现批量数据插入功能。Controller中对应的实现代码如下:importcom.example.demo.model.User;importcom.example.demo.service。impl.UserServiceImpl;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.ArrayList;importjava.util。List;@RestController@RequestMapping("/u")publicclassUserController{@AutowiredprivateUserServiceImpluserService;/***MP批量插入*/@RequestMapping("/savebatch")publicbooleansaveBatch(){Listlist=newArrayList<>();//(inti=0;i<1000;i++){Useruser=newUser();user.setName("test:"+i);user.setPassword("123456");list.add(user);}//批量插入returnuserService.saveBatch(list);}}③服务层代码(重点)接下来我们需要创建一个UserService接口,继承MP框架中的IService接口,实现代码如下:importcom.baomidou.mybatisplus.extension.service.IService;importcom.example.demo.model.User;publicinterfaceUserServiceextendsIService{}然后创建一个UserService实现类:importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importcom.example。demo.mapper.UserMapper;importcom.example.demo.model.User;importcom.example.demo.service.UserService;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplextendsServiceImplimplementsUserService{}PS:注意UserServiceImpl必须MP框架中要继承ServiceImpl,否则需要重写很多方法④Mapper层代码Mapper层的实现比较简单。只需要创建一个Mapper类就可以继承MP框架中的BaseMapper类。实现代码如下:importcom.baomidou.mybatisplus.core.mapper.BaseMapper;importcom。example.demo.model.User;importorg.apache.ibatis.annotations.Mapper;@MapperpublicinterfaceUserMapperextendsBaseMapper{}PS:BaseMapper提供了对一个对象(类)最基本的CRUD操作。小结在本文中,我们介绍了在MP(MyBatisPlus)中批量插入的具体实现步骤。其核心是通过调用MP中IService提供的saveBatch方法完成的。但是项目中没有引入MP框架怎么办?不是吗?你能和MP平躺吗?别着急,下一篇我们会讲另一种批量插入的方式(原生批量插入的实现),以及两者的优缺点分析。