MyBatis-Plus Guide: Features, Quick Start, CRUD Extensions, and Advanced Usage
This article introduces MyBatis‑Plus, an enhancement for MyBatis, outlining its lightweight features, step‑by‑step setup including database creation, Maven dependency, configuration, entity and mapper definitions, CRUD operations, pagination, optimistic locking, logical deletion, condition wrappers, and code generation utilities for rapid backend development.
Introduction
MyBatis‑Plus is an enhancement tool for MyBatis that adds powerful features without changing the core framework, allowing developers to reduce boilerplate code and improve development efficiency.
Key Features
Automatic injection of basic CRUD methods with no performance loss.
Support for lambda expressions to build type‑safe query conditions.
Built‑in distributed ID generator for primary‑key auto‑generation.
ActiveRecord mode where entity classes inherit Model for direct CRUD operations.
Integrated pagination plugin based on physical pagination.
Quick Start
1. Create Database and Table
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)
);2. Initialize Spring Boot Project
Add the MyBatis‑Plus starter dependency (avoid importing the original MyBatis dependency together):
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>3. Configure Data Source
# MySQL configuration
spring.datasource.username=root
spring.datasource.password=password123
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver4. Write Code
4.1 Entity Class
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
// 用户id
private Long id;
// 用户名
private String name;
// 年龄
private Integer age;
// 邮箱
private String email;
}4.2 Mapper Interface
@Mapper
@Repository
public interface UserMapper extends BaseMapper
{ }4.3 Service Logic Example
@Autowired
private UserMapper userMapper;
QueryWrapper
wrapper = new QueryWrapper<>();
userMapper.selectList(wrapper);5. Log Configuration
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImplCRUD Extensions
Insert
void insert(){
User user = new User();
user.setName("Alex");
user.setAge(42);
user.setEmail("[email protected]");
int result = userMapper.insert(user);
System.out.println(result);
System.out.println(user);
}Primary‑Key Generation Strategy
@TableName("user")
public class User implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
}Update
@Test
void updateTest(){
User user = new User();
user.setId(3L);
user.setName("docker&K8s");
int i = userMapper.updateById(user);
System.out.println(i);
}Optimistic Lock
Add a version field to the table and annotate it with @Version . Register the OptimisticLockerInterceptor bean to enable automatic version checking.
@Version
private Integer version; @Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}Pagination
Configure the PaginationInterceptor bean and use the Page object directly in queries.
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
Page
page = new Page<>(1, 5);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);Logical Delete
Enable logical deletion by adding a deleted column, annotating the field with @TableLogic , and configuring the delete values in application.properties .
@TableLogic
private Integer deleted; mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0Condition Wrapper
Use QueryWrapper to build complex SQL conditions programmatically.
QueryWrapper
wrapper = new QueryWrapper<>();
wrapper.eq("wx_user_id", WxUserId).eq("opinion_id", opinionId);
userMapper.selectOne(wrapper);Advanced Usage
Code Generator
The AutoGenerator can generate entity, mapper, service, and controller code based on database tables.
public class AutoCodeTool {
public static void main(String[] args) {
AutoGenerator autoCode = new AutoGenerator();
// global config, data source, package config, strategy config
autoCode.execute();
}
}Key configuration steps include setting the output directory, author, ID type, date type, Swagger support, data source URL, driver, credentials, package structure, naming strategy, Lombok model, REST style, logical delete field, automatic fill fields, and optimistic‑lock field.
Conclusion
Advantages
Most single‑table CRUD operations are available with minimal configuration.
Powerful condition builder satisfies diverse query needs.
Code generation via Maven plugin or programmatic API accelerates development.
ActiveRecord mode enables direct CRUD calls from entity classes.
Disadvantages
Strong coupling between DAO, service, and controller layers.
Generated SQL is hidden, making performance tuning and debugging harder.
Not well‑suited for large‑scale micro‑service architectures requiring fine‑grained control.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.