MyBatis 批量插入數(shù)據(jù)的 3 種方法!
先來簡單說一下 3 種批量插入功能分別是:
循環(huán)單次插入; MP 批量插入功能; 原生批量插入功能。
?
準(zhǔn)備工作
--?----------------------------
--?創(chuàng)建數(shù)據(jù)庫
--?----------------------------
SET?NAMES?utf8mb4;
SET?FOREIGN_KEY_CHECKS?=?0;
DROP?DATABASE?IF?EXISTS?`testdb`;
CREATE?DATABASE?`testdb`;
USE?`testdb`;
--?----------------------------
--?創(chuàng)建?user?表
--?----------------------------
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;
--?----------------------------
--?添加測試數(shù)據(jù)
--?----------------------------
INSERT?INTO?`user`?VALUES?(1,?'趙云',?'123456',?'2021-09-10?18:11:16');
INSERT?INTO?`user`?VALUES?(2,?'張飛',?'123456',?'2021-09-10?18:11:28');
INSERT?INTO?`user`?VALUES?(3,?'關(guān)羽',?'123456',?'2021-09-10?18:11:34');
INSERT?INTO?`user`?VALUES?(4,?'劉備',?'123456',?'2021-09-10?18:11:41');
INSERT?INTO?`user`?VALUES?(5,?'曹操',?'123456',?'2021-09-10?18:12:02');
SET?FOREIGN_KEY_CHECKS?=?1;

1.循環(huán)單次插入
import?com.example.demo.model.User;
import?com.example.demo.service.impl.UserServiceImpl;
import?org.junit.jupiter.api.Test;
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class?UserControllerTest?{
????//?最大循環(huán)次數(shù)
????private?static?final?int?MAXCOUNT?=?100000;
????@Autowired
????private?UserServiceImpl?userService;
????/**
?????*?循環(huán)單次插入
?????*/
????@Test
????void?save()?{
????????long?stime?=?System.currentTimeMillis();?//?統(tǒng)計(jì)開始時間
????????for?(int?i?=?0;?i?????????????User?user?=?new?User();
????????????user.setName("test:"?+?i);
????????????user.setPassword("123456");
????????????userService.save(user);
????????}
????????long?etime?=?System.currentTimeMillis();?//?統(tǒng)計(jì)結(jié)束時間
????????System.out.println("執(zhí)行時間:"?+?(etime?-?stime));
????}
}

?
2.MP 批量插入

<dependency>
????<groupId>com.baomidougroupId>
????<artifactId>mybatis-plus-boot-starterartifactId>
????<version>mybatis-plus-latest-versionversion>
dependency>
注意:mybatis-plus-latest-version 表示 MP 框架的最新版本號,可訪問 https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter 查詢最新版本號,但在使用的時候記得一定要將上面的 “mybatis-plus-latest-version”替換成換成具體的版本號,如 3.4.3 才能正常的引入框架。
① 控制器實(shí)現(xiàn)
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;
????/**
?????*?批量插入(自定義)
?????*/
????@RequestMapping("/mysavebatch")
????public?boolean?mySaveBatch(){
????????List?list?=?new?ArrayList<>();
????????//?待添加(用戶)數(shù)據(jù)
????????for?(int?i?=?0;?i?1000;?i++)?{
????????????User?user?=?new?User();
????????????user.setName("test:"+i);
????????????user.setPassword("123456");
????????????list.add(user);
????????}
????????return?userService.saveBatchCustom(list);
????}
}
② 業(yè)務(wù)邏輯層實(shí)現(xiàn)
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.beans.factory.annotation.Autowired;
import?org.springframework.stereotype.Service;
import?java.util.List;
@Service
public?class?UserServiceImpl?extends?ServiceImpl<UserMapper,User>
????????implements?UserService?{
????@Autowired
????private?UserMapper?userMapper;
????public?boolean?saveBatchCustom(List?list) {
????????return?userMapper.saveBatchCustom(list);
????}
}
③ 數(shù)據(jù)持久層實(shí)現(xiàn)
import?com.baomidou.mybatisplus.core.mapper.BaseMapper;
import?com.example.demo.model.User;
import?org.apache.ibatis.annotations.Mapper;
import?java.util.List;
@Mapper
public?interface?UserMapper?extends?BaseMapper<User>{
????boolean?saveBatchCustom(List?list) ;
}
MP 性能測試
import?com.example.demo.model.User;
import?com.example.demo.service.impl.UserServiceImpl;
import?org.junit.jupiter.api.Test;
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.boot.test.context.SpringBootTest;
import?java.util.ArrayList;
import?java.util.List;
@SpringBootTest
class?UserControllerTest?{
????//?最大循環(huán)次數(shù)
????private?static?final?int?MAXCOUNT?=?100000;
????@Autowired
????private?UserServiceImpl?userService;
????/**
?????*?MP?批量插入
?????*/
????@Test
????void?saveBatch()?{
????????long?stime?=?System.currentTimeMillis();?//?統(tǒng)計(jì)開始時間
????????List?list?=?new?ArrayList<>();
????????for?(int?i?=?0;?i?????????????User?user?=?new?User();
????????????user.setName("test:"?+?i);
????????????user.setPassword("123456");
????????????list.add(user);
????????}
????????//?MP?批量插入
????????userService.saveBatch(list);
????????long?etime?=?System.currentTimeMillis();?//?統(tǒng)計(jì)結(jié)束時間
????????System.out.println("執(zhí)行時間:"?+?(etime?-?stime));
????}
}

MP 源碼分析


?
3.原生批量插入
① 業(yè)務(wù)邏輯層擴(kuò)展
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.beans.factory.annotation.Autowired;
import?org.springframework.stereotype.Service;
import?java.util.List;
@Service
public?class?UserServiceImpl?extends?ServiceImpl<UserMapper,?User>
????????implements?UserService?{
????@Autowired
????private?UserMapper?userMapper;
????public?boolean?saveBatchByNative(List?list) ?{
????????return?userMapper.saveBatchByNative(list);
????}
}
② 數(shù)據(jù)持久層擴(kuò)展
import?com.baomidou.mybatisplus.core.mapper.BaseMapper;
import?com.example.demo.model.User;
import?org.apache.ibatis.annotations.Mapper;
import?java.util.List;
@Mapper
public?interface?UserMapper?extends?BaseMapper<User>?{
????boolean?saveBatchByNative(List?list) ;
}
③ 添加 UserMapper.xml
"1.0"?encoding="UTF-8"?>
"-//mybatis.org//DTD?Mapper?3.0//EN"?"http://mybatis.org/dtd/mybatis-3-mapper.dtd">"com.example.demo.mapper.UserMapper">
????"saveBatchByNative">
????????INSERT?INTO?`USER`(`NAME`,`PASSWORD`)?VALUES
????????"list"?separator=","?item="item">
????????????(#{item.name},#{item.password})
????????
????
原生批量插入性能測試
import?com.example.demo.model.User;
import?com.example.demo.service.impl.UserServiceImpl;
import?org.junit.jupiter.api.Test;
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.boot.test.context.SpringBootTest;
import?java.util.ArrayList;
import?java.util.List;
@SpringBootTest
class?UserControllerTest?{
????//?最大循環(huán)次數(shù)
????private?static?final?int?MAXCOUNT?=?100000;
????@Autowired
????private?UserServiceImpl?userService;
????
????/**
?????*?原生自己拼接?SQL,批量插入
?????*/
????@Test
????void?saveBatchByNative()?{
????????long?stime?=?System.currentTimeMillis();?//?統(tǒng)計(jì)開始時間
????????List?list?=?new?ArrayList<>();
????????for?(int?i?=?0;?i?????????????User?user?=?new?User();
????????????user.setName("test:"?+?i);
????????????user.setPassword("123456");
????????????list.add(user);
????????}
????????//?批量插入
????????userService.saveBatchByNative(list);
????????long?etime?=?System.currentTimeMillis();?//?統(tǒng)計(jì)結(jié)束時間
????????System.out.println("執(zhí)行時間:"?+?(etime?-?stime));
????}
}

缺點(diǎn)分析
解決方案
--?設(shè)置最大執(zhí)行?SQL?為?10M
set?global?max_allowed_packet=10*1024*1024;

注意:以上命令需要在 MySQL 連接的客戶端中執(zhí)行。

總結(jié)
有道無術(shù),術(shù)可成;有術(shù)無道,止于術(shù)
歡迎大家關(guān)注Java之道公眾號
好文章,我在看??
