Implementing Batch Insert with MyBatis-Plus in Java

This article explains how to improve database insertion performance in Java by replacing per‑iteration inserts with MyBatis‑Plus’s saveBatch method, detailing dependency setup, schema creation, entity, controller, service, and mapper code for efficient bulk operations.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Implementing Batch Insert with MyBatis-Plus in Java

When reviewing code, the author discovered that inserting records inside a for loop creates a new database connection for each iteration, which dramatically reduces performance even though the final result is unchanged. The article uses a delivery‑analogy to illustrate why batch insertion is far more efficient.

The solution is to use MyBatis‑Plus (MP) and its saveBatch method to insert many rows in a single operation. The article walks through the complete implementation steps.

1. Add MP dependency

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>mybatis-plus-latest-version</version>
</dependency>

Replace mybatis-plus-latest-version with the actual version number (e.g., 3.4.3).

2. Create database and table

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
DROP DATABASE IF EXISTS `testdb`;
CREATE DATABASE `testdb`;
USE `testdb`;

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NULL DEFAULT NULL,
  `password` varchar(255) NULL DEFAULT NULL,
  `createtime` datetime NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=6 CHARSET=utf8mb4;

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,'关羽','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;

3. Entity class

import lombok.Getter;
import lombok.Setter;
import java.util.Date;

@Getter
@Setter
public class User {
    private int id;
    private String name;
    private String password;
    private Date createtime;
}

4. Controller layer

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 insert */
    @RequestMapping("/savebatch")
    public boolean saveBatch() {
        List<User> list = new ArrayList<>();
        // prepare 1000 users
        for (int i = 0; i < 1000; i++) {
            User user = new User();
            user.setName("test:" + i);
            user.setPassword("123456");
            list.add(user);
        }
        // batch insert
        return userService.saveBatch(list);
    }
}

5. Service layer

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.model.User;

public interface UserService extends IService<User> {
}

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;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

6. Mapper layer

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.model.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

The article concludes that using MP’s saveBatch dramatically reduces the number of database round‑trips, improving performance. It also hints at a future discussion of native JDBC batch inserts and a comparison of the two approaches.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaperformanceSQLSpring Bootmybatis-plusBatch Insert
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.