When to Use MyBatis-Plus: Pros, Cons, and Best Practices
This article examines MyBatis-Plus, highlighting its convenient CRUD shortcuts and pagination features while warning about maintenance challenges, magic strings, and limited support for complex SQL, and offers practical recommendations for using LambdaQueryWrapper and organizing queries in backend Java projects.
Preface
MyBatis-Plus (MP) has been controversial since its release, with both supporters and critics.
Advantages
Simplified Operations
MP allows CRUD operations without writing XML, e.g.:
nodeMapper.selectById(1);
nodeMapper.deleteById(2);
nodeMapper.updateById(new Node());
nodeMapper.insert(new Node());However, default methods select all columns, which is poor practice; using QueryWrapper or LambdaQueryWrapper lets you specify fields.
nodeMapper.selectOne(new QueryWrapper<Node>().eq("id",1).select("id"));LambdaQueryWrapper improves type safety and avoids magic strings:
Node node = nodeMapper.selectOne(new LambdaQueryWrapper<Node>()
.eq(Node::getId, 1)
.select(Node::getId));When a column name changes, MP may not raise an error, leading to silent failures:
Using LambdaQueryWrapper solves the problem by tying the query to the entity’s getter methods:
Node node = nodeMapper.selectOne(new LambdaQueryWrapper<Node>()
.eq(Node::getId, 1)
.select(Node::getId));Pagination is straightforward:
LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(UserInfo::getAge, 20);
Page<UserInfo> queryPage = new Page<>(page, limit);
IPage<UserInfo> iPage = userInfoMapper.selectPage(queryPage, queryWrapper);
Long total = iPage.getTotal();
List<UserInfo> list = iPage.getRecords();Disadvantages
Complex SQL, multi‑table joins, and custom queries are cumbersome with MP. For example, using @Select with ${ew.customSqlSegment} leads to unreadable code, and MP’s built‑in methods like selectById are not suitable for production.
Simple Summary
MP is convenient for simple single‑table queries but should be avoided for complex SQL. Organize MP queries in a dedicated package, prefer LambdaQueryWrapper for maintainability, use built‑in pagination, and avoid selectById and other generic methods for production code.
Conclusion
Do not rely on MP for complex statements; use it only for straightforward CRUD and pagination.
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.
Java Interview Crash Guide
Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.
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.
