Unlock MyBatis-Plus: From Zero-Code CRUD to Secure, Scalable DAO Architecture
This article introduces MyBatis-Plus, explains its core zero‑invasion features such as effortless single‑table CRUD, powerful Lambda condition builders, and a rich plugin system, then provides practical guidelines and code examples for building secure, high‑performance DAO layers in microservice back‑ends.
1. MyBatis-Plus Overview: More Than an Enhancement, a Refactor
MyBatis-Plus can be seen as "MyBatis + Swiss‑army‑knife skin + delete‑protection safety pin"—it retains MyBatis native features while offering zero‑intrusion single‑table operations.
Its core value lies in three aspects:
Swiss‑army‑knife convenience : upgrades XML configuration to Lambda expressions, enabling complex operations with minimal code.
Safety‑pin level security : intercepts dangerous statements like "delete from table" to prevent accidental data loss.
Zero‑intrusion compatibility : works with existing MyBatis code without modification, allowing smooth migration.
2. Core Features: A "All‑Purpose Toolbox" for Single‑Table Operations
All functionality is exposed through the BaseMapper interface, eliminating the need for manual implementations.
2.1 Basic CRUD: Zero‑Code Single‑Table Operations
BaseMapper encapsulates all basic single‑table methods; 90% of business needs are satisfied without writing SQL. Key methods include:
int insert(T entity) – inserts a record, ignoring null properties.
boolean insertOrUpdate(T entity) – inserts or updates based on primary key.
int deleteById(Serializable id) – deletes a record by primary key.
int deleteByIds(Collection idList) – batch delete.
int updateById(T entity) – updates by primary key.
T selectById(Serializable id) – selects a record by primary key.
List selectList(Wrapper queryWrapper) – batch query; beware of full‑table scans when wrapper is null.
2.2 Condition Builder: Elegant Complex Queries
The condition builder is the "soul" of MyBatis‑Plus, offering four styles:
QueryWrapper : basic builder using string field names, e.g., eq("name","张三").
LambdaQueryWrapper : lambda‑based builder, e.g., eq(User::getName,"张三"); recommended for compile‑time safety.
UpdateWrapper / LambdaUpdateWrapper : for constructing update conditions.
Using LambdaQueryWrapper prevents misspelled fields and type mismatches, improves readability, and enables automatic refactoring.
// ❌ Not recommended: string‑based query
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","张三").gt("age",18);
// ✅ Recommended: lambda‑based query
LambdaQueryWrapper<User> lambda = new LambdaQueryWrapper<>();
lambda.eq(User::getName,"张三").gt(User::getAge,18);2.3 Rich Plugin Collection: "Universal Interfaces"
MyBatis‑Plus uses MybatisPlusInterceptor to provide plugins such as: PaginationInnerInterceptor – automatic pagination (must be configured). BlockAttackInnerInterceptor – blocks full‑table update/delete. OptimisticLockerInnerInterceptor – optimistic locking via version field. TenantLineInnerInterceptor – multi‑tenant automatic tenant‑ID condition. IllegalSQLInnerInterceptor – enforces SQL best practices (e.g., disallow SELECT *).
3. Usage Recommendations: Write Efficient, Safe MP Code
3.1 Prefer Lambda Condition Builder
Avoid string‑based conditions; LambdaQueryWrapper catches missing fields and type errors at compile time.
3.2 Null‑Value Handling in Conditions
MP supports conditional addition, reducing redundant if checks:
// ❌ Not recommended: many ifs
if (StringUtils.isNotBlank(name)) { wrapper.eq(User::getName, name); }
if (age != null) { wrapper.eq(User::getAge, age); }
// ✅ Recommended: conditional addition
wrapper.eq(StringUtils.isNotBlank(name), User::getName, name)
.eq(Objects.nonNull(age), User::getAge, age);3.3 Explicit Select Fields for Efficiency
Specify fields to leverage index coverage and reduce data transfer:
// ❌ Full‑field query
List<User> users1 = userMapper.selectList(lambdaWrapper);
// ✅ Select needed fields only
lambdaWrapper.select(User::getId, User::getName, User::getAge);
List<User> users2 = userMapper.selectList(lambdaWrapper);4. Practical Development: From "Usable" to "Well‑Used"
4.1 QueryCondition for Microservice RPC
In microservice architectures, exposing QueryWrapper directly causes serialization overhead and dependency issues. Replace it with a lightweight QueryCondition that bundles query fields, order fields, selected fields, and pagination parameters.
Structure of QueryCondition:
queryFieldList – list of field‑name, operator, and logical connector.
orderFieldList – sorting fields and direction.
selectFieldList – fields to return, avoiding SELECT *.
pageNum / pageSize – pagination parameters.
public class QueryCondition {
private List<String> selectFieldList;
private List<QueryField> queryFieldList;
private List<OrderField> orderFieldList;
private int pageNum;
private int pageSize;
}A type‑safe builder QueryConditionBuilder simplifies creation:
QueryCondition condition = QueryConditionBuilder.builder()
.select(User::getId, User::getName)
.eq(User::getStatus,1)
.like(User::getName,"张")
.in(User::getType,Arrays.asList(1,2,3))
.orderByDesc(User::getCreateTime)
.pageNum(1).pageSize(5)
.build();4.2 Fast Integration: 3‑Step Single‑Table CRUD
Define a contract interface extending BaseDao, implement it by extending AbstractBaseDaoImpl, and configure master/slave data sources. The resulting service provides CRUD operations and supports QueryCondition for flexible queries.
4.3 Extending BaseMapper with Custom Methods
Custom mapper interfaces can add methods such as int countByEntity(T entity). Implement them via a custom AbstractMethod and register with a SqlInjector.
4.4 Built‑in Plugins for System Safety
Two plugins protect production environments:
FullTableScanInterceptor – blocks queries without WHERE conditions.
BlockFullTableOperationInterceptor – blocks updates/deletes without conditions.
5. Conclusion: Why MyBatis‑Plus Is Worth Using
MyBatis‑Plus delivers a dramatic boost in DAO development efficiency with minimal migration cost, provides lambda‑based safety, plugin‑driven security and extensibility, and standardizes coding practices, reducing onboarding time and preventing runtime SQL issues.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
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.
