Comprehensive Guide to MyBatis-Plus: CRUD, Annotations, Condition Builders, Pagination, and Advanced Features
This article provides a detailed tutorial on using MyBatis-Plus in Java, covering setup, entity and mapper definitions, CRUD operations, annotations, condition builders, pagination, AR mode, logical deletion, automatic field filling, optimistic locking, performance analysis, multi‑tenant support, dynamic table names, configuration options, and code generation.
Overview
MyBatis-Plus (MP) is a powerful enhancement for MyBatis that simplifies CRUD operations, provides annotations, condition builders, pagination, and advanced features such as logical deletion, optimistic locking, and multi‑tenant support.
Quick Start
The guide shows how to create a Spring Boot project, add MP dependencies, configure application.yml, and set up the basic entity, mapper, service, and controller for a User table.
Core Features
Annotations
MP offers annotations like @TableName, @TableId, @TableField, @Version, and @TableLogic to map Java fields to database columns, define primary‑key strategies, and enable logical deletion.
CRUD Interfaces
The BaseMapper interface provides methods such as insert, deleteById, selectById, updateById, and wrapper‑based queries, while the service layer uses IService for additional batch operations.
Condition Builder
Wrapper classes ( QueryWrapper, UpdateWrapper) and their lambda variants ( LambdaQueryWrapper, LambdaUpdateWrapper) enable fluent construction of WHERE clauses with methods like eq, like, between, nested, and apply. Logical conditions can be toggled with a boolean condition parameter.
Pagination
Configure MybatisPlusInterceptor with PaginationInnerInterceptor and use Page objects together with selectPage or custom SQL for paginated queries.
AR Mode
Entities can extend Model to perform active‑record style operations directly on the object, such as insert(), selectById(), updateById(), and deleteById().
Advanced Features
Includes logical deletion (automatically adds WHERE deleted = 0), automatic field filling via MetaObjectHandler, optimistic locking with @Version, performance analysis using p6spy, multi‑tenant SQL parsing, and dynamic table name handling.
Configuration
Global and per‑entity settings in application.yml control primary‑key strategies, field strategies, logical delete fields, table prefixes, and more.
Code Generator
The AutoGenerator can generate entity, mapper, service, and controller code based on the database schema, reducing boilerplate.
IT Xianyu
We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.
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.
