In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Xiaobian to share with you how MyBatis Plus to achieve batch data insertion function, I believe most people still do not know how to share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
preface
Recently, when reviewing the small partner code, I found a small problem. The small partner actually carried out insert (insert) database operations in the for loop, which will lead to connection, insertion, and disconnection operations every time the loop is performed, resulting in certain performance problems. The simplified code is as follows:
/** * insert */@RequestMapping("/save")public Object save() { boolean flag = false; //return result //Data to be added (user) for (int i = 0; i < 1000; i++) { User user = new User(); user.setName("test:"+i); user.setPassword("123456"); //insert data flag = userService.save(user); if(! flag) break; } return flag;}
This does not change the final execution result of the program, but it will have a great impact on the execution efficiency of the program. For example, if you want to send 10 pieces of goods from location A to location B, you can choose the plan of sending 1 piece at a time and sending 10 times; you can also choose the plan of sending 10 pieces at a time and sending 1 time. Which one would you choose? This is the problem of repeated insertions and batch insertions.
PS: The larger the amount of data to insert, the shorter the batch insertion time (compared to repeated insertions) and the greater the advantage.
batch insertion scheme
In this article we use MyBatis-Plus (hereinafter referred to as MP) comes with the saveBatch method, to achieve the batch insertion of data, because MP is not the focus of this article, so we will not introduce here, if there are unfamiliar friends can go to his official self: https://baomidou.com/guide/, we focus on this article to introduce MP to achieve batch insertion of specific steps.
1. Introduction of MP framework
First, open your pom.xml file and add the following to the file:
com.baomidou mybatis-plus-boot-starter mybatis-plus-latest-version
Note: mybatis-plus-latest-version indicates the latest version number of the MP framework. You can visit https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter to query the latest version number, but remember to replace the above "mybatis-plus-latest-version" with a specific version number, such as 3.4.3, to introduce the framework normally.
2. Creating databases and tables
This step can be omitted and is mainly used for the implementation of the functions of this article. The scripts for creating databases and data tables are as follows:
SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;DROP DATABASE IF EXISTS `testdb`;CREATE DATABASE `testdb`;USE `testdb`;-----------------------------Create user table--------------------------DROP TABLE IF EXISTS `user`; CREATE TABLE `user`( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL, `createtime` datetime NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;-- --------------------------------Add Test Data----------------------Insert INTO `user` VALUES (1, 'Zhao Yun',' 123456','2021-09-10 18:11: 16');INSERT INTO `user` VALUES (2, 'Zhang Fei',' 123456','2021-09-10 18:11: 28');INSERT INTO `user` VALUES (3, 'Guan Yu',' 123456','2021-09-10 18:11: 34');INSERT INTO `user` VALUES (4, 'Liu Bei',' 123456','2021-09-10 18:11: 41');INSERT INTO `user` VALUES (5, ' Cao Cao','123456','2021-09-10 18:12: 02');SET FOREIGN_KEY_CHECKS = 1;3. Specific code implementation (emphasis)
① Entity class
First, create the User entity class corresponding to the database:
import lombok.Getter;import lombok.Setter;import java.util.Date;@Getter@Setterpublic class User { private int id; private String name; private String password; private Date createtime;}
② Controller layer code
The core of this article is to use the saveBatch method provided by the IService class in the MP framework to implement the batch data insertion function. The corresponding implementation code in the Controller is as follows:
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")public class UserController { @Autowired private UserServiceImpl userService; /** * MP Batch Insertion */ @RequestMapping("/savebatch") public boolean saveBatch() { List list = new ArrayList(); //Data to be added (user) for (int i = 0; i < 1000; i++) { User user = new User(); user.setName("test:"+i); user.setPassword("123456"); list.add(user); } //Batch insertion return userService.saveBatch(list); }}
③ Service layer code (emphasis)
Next, we want to create a UserService interface, inheriting the IService interface in the MP framework, and the implementation code is as follows:
import com.baomidou.mybatisplus.extension.service.IService;import com.example.demo.model.User;public interface UserService extends IService {}
Then create an implementation class for UserService:
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.example.demo.mapper.UserMapper;import com.example.demo.model.User;import com.example.demo.service.UserService;import org.springframework.stereotype.Service;@Servicepublic class UserServiceImpl extends ServiceImpl implements UserService {}
PS: Note that UserServiceImpl must inherit ServiceImpl in MP framework, otherwise it will have to rewrite many methods.
④ Mapper layer code
The implementation of the Mapper layer is relatively simple, just need to create a Mapper class to inherit the BaseMapper class in the MP framework, the implementation code is as follows:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.example.demo.model.User;import org.apache.ibatis.annotations.Mapper;@Mapperpublic interface UserMapper extends BaseMapper{}
PS: BaseMapper provides the most basic CRUD operations on an object (class).
The above is "MyBatis Plus how to achieve batch data insertion function" all the content of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.