Backend Development 15 min read

MyBatis‑Plus Tutorial: Creating Databases, Defining Tables, CRUD Operations, Optimistic Locking, Logical Deletion, Performance Analysis, and Code Generation in Spring Boot

This article provides a step‑by‑step guide for using MyBatis‑Plus with Spring Boot, covering database and table creation, entity and mapper definitions, CRUD examples, automatic field filling, optimistic and logical deletion, performance plugins, query wrappers, and a code generator for rapid development.

Top Architect
Top Architect
Top Architect
MyBatis‑Plus Tutorial: Creating Databases, Defining Tables, CRUD Operations, Optimistic Locking, Logical Deletion, Performance Analysis, and Code Generation in Spring Boot

Preface

The tutorial demonstrates how to integrate MyBatis‑Plus into a Spring Boot project for efficient database operations.

Create Database and Table

A MySQL database named mybatis_plus is created, followed by a user table with fields id , name , age , and email . Sample data is inserted using the following SQL:

DROP TABLE IF EXISTS user;
CREATE TABLE user (
  id BIGINT(20) NOT NULL COMMENT '主键ID',
  name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
  age INT(11) NULL DEFAULT NULL COMMENT '年龄',
  email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
  PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

Typical development tables also include version , deleted , gmt_create , and gmt_modified columns.

Project Initialization

A Spring Boot project is initialized and the following Maven dependencies are added:

mysql
mysql-connector-java
org.projectlombok
lombok
com.baomidou
mybatis-plus-boot-starter
3.0.5

It is recommended not to import both MyBatis and MyBatis‑Plus simultaneously to avoid version conflicts.

Database Connection

The application.yml file is configured with the datasource URL, driver, username, and password:

spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root

Entity and Mapper

The User entity uses Lombok annotations:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
  private Long id;
  private String name;
  private Integer age;
  private String email;
}

The mapper interface extends BaseMapper<User> and is annotated with @Repository :

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kuang.pojo.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper
{
  // CRUD methods are provided by BaseMapper
}

Testing CRUD Operations

Insertion example (ID is auto‑generated):

@Test
public void testInsert() {
  User user = new User();
  user.setName("kwhua_mybatis-plus_insertTest");
  user.setAge(15);
  user.setEmail("[email protected]");
  int result = userMapper.insert(user);
  System.out.println(result);
  System.out.println(user);
}

Update by ID:

@Test
public void testUpdate() {
  User user = new User();
  user.setId(1302223874217295874L);
  user.setName("kwhua_mybatis-plus_updateTest");
  user.setAge(20);
  int i = userMapper.updateById(user);
  System.out.println(i);
}

Automatic Field Filling

Two strategies are shown: database‑level defaults and code‑level filling using @TableField(fill = FieldFill.INSERT) for gmt_create and @TableField(fill = FieldFill.INSERT_UPDATE) for gmt_modified . A custom MetaObjectHandler implementation populates these fields during insert and update.

Optimistic Locking

The version column is added to the table and annotated with @Version in the entity. An OptimisticLockerInterceptor bean is registered, and update operations automatically check the version value to prevent lost updates.

Logical Deletion

Logical deletion uses a deleted column annotated with @TableLogic . The global configuration sets logic-delete-value: 1 and logic-not-delete-value: 0 . A LogicSqlInjector bean enables the feature.

Performance Analysis Plugin

A PerformanceInterceptor bean limits SQL execution time (e.g., 100 ms) and formats the output, useful in development and testing environments.

Query Wrapper (Condition Builder)

Examples of using QueryWrapper<User> to build dynamic queries:

QueryWrapper
wrapper = new QueryWrapper<>();
wrapper.isNotNull("name")
       .isNotNull("email")
       .ge("age", 18);
userMapper.selectList(wrapper).forEach(System.out::println);

// Equality condition
wrapper.eq("name", "kwhua");
User user = userMapper.selectOne(wrapper);
System.out.println(user);

Code Generator

A Java class demonstrates how to configure MyBatis‑Plus’s AutoGenerator to generate entity, mapper, service, and controller code for tables user and course . Configuration includes global settings, data source, package structure, naming strategy, Lombok model, logical delete field, automatic timestamp fields, optimistic‑lock field, and REST controller style.

Conclusion

The tutorial covers end‑to‑end usage of MyBatis‑Plus in a Spring Boot application, from schema creation to advanced features such as optimistic locking, logical deletion, performance monitoring, dynamic query building, and automatic code generation, providing a solid foundation for backend developers.

code generationDatabaseSpring BootMyBatis-PlusCRUDOptimistic Locking
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login 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.