MyBatis-Plus Overview, Features, and Practical Tutorial for Java Backend Development
This article introduces MyBatis-Plus, an enhancement library for MyBatis, outlines its major advantages, explains performance‑analysis and advanced plugins, and provides a step‑by‑step tutorial with code examples for integrating, configuring, and using the framework in Java Spring Boot projects.
MyBatis-Plus (MP) is an enhancement tool for MyBatis that adds rich functionality while keeping the original MyBatis unchanged, allowing developers to quickly perform single‑table CRUD operations with minimal configuration.
Key Advantages
Lightweight dependency – only MyBatis and MyBatis‑Spring are required.
Automatic injection of basic CRUD at startup with negligible performance overhead.
Built‑in SQL injection filter to protect against injection attacks.
General CRUD support via built‑in Mapper and Service classes.
Multiple primary‑key strategies, including distributed ID generators.
Mapper XML hot‑loading, allowing XML‑free CRUD for simple cases.
ActiveRecord style calls by extending the Model class.
Code generator that can produce multi‑layer code (Entity, Mapper, Service, Controller) with customizable templates.
Global custom method injection (Write once, use anywhere).
Automatic keyword escaping for database reserved words.
Built‑in pagination plugin supporting most mainstream databases.
Performance analysis plugin that logs SQL statements and execution time.
Global interceptor plugin that prevents accidental full‑table delete or update operations.
Performance Analysis
The performance analysis feature is implemented via AOP: an interceptor is inserted into MyBatis execution to collect timing data before and after each SQL statement.
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.9</version>
</dependency>Configuration example (Spring Boot):
@Configuration
public class MyBatisPlusConfig {
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000); // 1 second threshold
performanceInterceptor.setFormat(true); // enable SQL formatting
return performanceInterceptor;
}
}Getting Started Tutorial
1. Add the Maven dependency (or Gradle equivalent):
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.9</version>
</dependency>2. Configure the database connection (example using application.yml ).
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/your_database?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: root3. Create an entity class and a Mapper interface.
@Data
@TableName("your_table_name")
public class YourEntity {
@TableId(type = IdType.AUTO)
private Long id;
// other fields ...
} public interface YourMapper extends BaseMapper<YourEntity> {}4. Enable Mapper scanning in the Spring Boot main class.
@SpringBootApplication
@MapperScan("your.package.path")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}5. Basic CRUD operations can be performed directly via the injected Mapper:
// Insert
YourEntity entity = new YourEntity();
// set properties
yourMapper.insert(entity);
// Query
YourEntity byId = yourMapper.selectById(id);
List<YourEntity> list = yourMapper.selectList(null);
// Update
yourMapper.updateById(updatedEntity);
// Delete
yourMapper.deleteById(id);Advanced Features
Pagination: Add the pagination interceptor and use Page<YourEntity> together with selectPage .
Condition Builder: Use QueryWrapper or LambdaQueryWrapper to build complex queries.
Code Generator: Configure AutoGenerator with data source, global, and strategy settings, then call mpg.execute() to generate Entity, Mapper, Service, and Controller code.
Logical Deletion: Define a deleted field, configure logic-delete-field , and annotate the field with @TableLogic .
Enum Support: Use @EnumValue or implement IEnum for automatic enum handling.
Automatic Field Filling: Annotate fields with @TableField(fill = FieldFill.INSERT) or INSERT_UPDATE and implement MetaObjectHandler to set timestamps and version numbers.
Real‑World Use Cases
Examples include logical deletion, generic enum handling, and automatic timestamp filling, each demonstrated with configuration snippets and Java code.
Conclusion
MyBatis-Plus is a powerful Java persistence framework that greatly improves development efficiency with its lightweight dependencies, extensive plugins, and rich feature set. While third‑party plugins may introduce compatibility concerns and documentation lag, the overall benefits—such as simplified CRUD, robust pagination, performance monitoring, and code generation—make it a recommended choice for both small and large‑scale Java applications.
Top Architecture Tech Stack
Sharing Java and Python tech insights, with occasional practical development tool tips.
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.