MyBatis-Plus Overview and Quick‑Start Guide
This article introduces MyBatis‑Plus, an enhancement tool for MyBatis that provides non‑intrusive CRUD operations, lambda queries, automatic primary‑key generation, pagination, optimistic locking, logical deletion, performance analysis, and a code generator, and demonstrates how to set up a Spring Boot project with full code examples.
MyBatis‑Plus Overview
MyBatis‑Plus (MP) is an enhancement library for MyBatis that adds powerful features without changing the core framework, aiming to simplify development and improve efficiency.
Key Features
Non‑intrusive: It does not affect existing projects.
Low overhead: Basic CRUD is injected at startup with negligible performance impact.
Powerful CRUD: Built‑in generic Mapper and Service allow most single‑table operations with minimal configuration, plus a rich condition builder.
Lambda support: Lambda expressions enable type‑safe query construction.
Primary‑key generation: Supports four strategies, including a distributed ID generator (Sequence).
ActiveRecord mode: Entities can extend Model to gain CRUD methods directly.
Global custom operations: One‑time method injection usable anywhere.
Code generator: Generates Mapper, Model, Service, Controller layers via code or Maven plugin.
Pagination plugin: Physical pagination with automatic handling.
Multi‑DB pagination support: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, PostgreSQL, SQLServer.
Performance analysis plugin: Outputs SQL statements and execution time.
Global interceptor: Prevents accidental full‑table delete or update.
Quick Start
1. Create a database and table:
DROP TABLE IF EXISTS user;
CREATE TABLE user (
id BIGINT(20) NOT NULL COMMENT 'Primary Key ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT 'Name',
age INT(11) NULL DEFAULT NULL COMMENT 'Age',
email VARCHAR(50) NULL DEFAULT NULL COMMENT 'Email',
PRIMARY KEY (id)
);2. Insert sample data:
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]');3. Add the Maven dependency to a Spring Boot project:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>Latest Version</version>
</dependency>4. Configure the datasource in application.yml (or application.properties):
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&useSSL=true&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=2330315. Define the entity class:
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// constructors, getters, setters omitted for brevity
}6. Create the mapper interface extending BaseMapper<User>:
@Repository
public interface UserMapper extends BaseMapper<User> {
// All CRUD methods are provided by BaseMapper
}Log Configuration
To display SQL details during tests, add:
# Log configuration
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImplCRUD Extensions
Insert Operation
// Test insert
@Test
public void testInsert() {
User user = new User();
user.setName("派大星学Java");
user.setAge(16);
user.setEmail("[email protected]");
int insert = userMapper.insert(user); // ID is auto‑generated
System.out.println(insert);
System.out.println(user); // ID is filled back
}The default primary‑key strategy is ID_WORKER (global unique ID). The article also explains the Snowflake algorithm.
Auto‑Increment Primary Key
Configure with @TableId(type = IdType.AUTO) on the entity field and ensure the column is set to auto‑increment in the database.
Logical Deletion
Add a deleted column, annotate the field with @TableLogic, and configure values:
# Logical delete configuration
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0Optimistic Lock
Add a version field annotated with @Version and register OptimisticLockerInterceptor as a bean.
Pagination
Register PaginationInterceptor and use Page<User> page = new Page<>(1, 5); with userMapper.selectPage(page, null).
Performance Analysis Plugin
Register PerformanceInterceptor (active in dev or test profiles) and set a maximum execution time, e.g., 100 ms.
Condition Builder
Examples of using QueryWrapper<User> for non‑null checks, range queries, like queries, ordering, sub‑queries, etc.
Code Generator
Use AutoGenerator to generate entity, mapper, service, and controller code. The sample configuration sets output directory, author, naming strategy, Lombok model, REST style, and table inclusion.
public class Generator {
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// Global config
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("派大星");
gc.setOpen(false);
gc.setFileOverride(false);
gc.setServiceName("%sService");
gc.setIdType(IdType.ID_WORKER_STR);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// Data source config
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/kuangstudy?useUnicode=true&characterEncoding=utf-8&useSSL=false");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("233031");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// Package config
PackageConfig pc = new PackageConfig();
pc.setModuleName("pdx");
pc.setParent("com");
pc.setController("controller");
pc.setEntity("pojo");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// Strategy config
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("pdx_download");
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setTablePrefix("i_");
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// Execute generation
mpg.execute();
}
}The article concludes that mastering all CRUD operations and their extensions in MyBatis‑Plus is essential for backend development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
