Mybatis-Plus vs Mybatis-Flex: Which ORM Framework Is Best for Your Project?
This article provides a detailed comparison between Mybatis-Plus and Mybatis-Flex, examining their design philosophies, core mechanisms, feature sets, performance benchmarks, database support, dependency weight, and community maturity, and offers practical guidance on choosing the right framework for different project scenarios.
Mybatis-Plus Overview
Mybatis-Plus enhances MyBatis without altering its core behavior. It is fully compatible with MyBatis and provides many out‑of‑the‑box functions.
Native MyBatis requires a Mapper interface, an XML mapping file and an entity class for a simple insert, often dozens of lines of code.
Mybatis-Plus needs only an entity class that extends BaseMapper and a call such as userMapper.insert(user), reducing code by more than 60%.
Enhancement Mechanism
MyBatis core execution chain:
mapper.selectById(1L) → MapperProxy.invoke() → MapperMethod.execute() → DefaultSqlSession.selectOne() → CachingExecutor.query() → SimpleExecutor.doQuery() → StatementHandler.prepare() → ParameterHandler.setParameters() → ResultSetHandler.handleResultSets()
Mybatis-Plus inserts custom logic via MyBatis Interceptor mechanism. MybatisPlusInterceptor composes a responsibility chain of interceptors such as PaginationInnerInterceptor, OptimisticLockerInnerInterceptor and TenantLineInnerInterceptor, each handling a single cross‑cutting concern.
Three‑step core process :
Startup scanning and injection : During Spring Boot auto‑configuration, MybatisPlusAutoConfiguration scans all interfaces extending BaseMapper, generates a proxy for each, and injects common CRUD SQL into MyBatis MappedStatement collection via MybatisSqlInjector.
Dynamic proxy at method call : When baseMapper.insert(entity) is invoked, the proxy reads annotations like @TableId and @TableField, assembles the full INSERT SQL, and hands it to MyBatis.
Condition builder SQL assembly : AbstractWrapper and its subclasses ( QueryWrapper, UpdateWrapper) turn chain‑style calls into parameterised SQL fragments. Lambda expressions are parsed via SerializedLambda, eliminating hard‑coded strings.
Plugin and interceptor types include Executor (full‑stage interception), StatementHandler (SQL construction), ParameterHandler (parameter setting) and ResultSetHandler (result processing).
Key Features
Zero‑SQL CRUD :
public interface UserMapper extends BaseMapper<User> { }
User user = userMapper.selectById(1L);
List<User> users = userMapper.selectList(wrapper);
userMapper.insert(user);
userMapper.updateById(user);
userMapper.deleteById(1L);LambdaQueryWrapper (type‑safe condition building) :
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(User::getName, "张三")
.gt(User::getAge, 18)
.orderByDesc(User::getCreateTime);
List<User> users = userMapper.selectList(wrapper);Physical pagination (avoids in‑memory pagination):
@GetMapping("/list")
public IPage<User> list(Page<User> page) {
return userService.page(page); // SELECT * FROM user LIMIT (page-1)*size, size
}Optimistic lock using @Version:
@Version
private Integer version;Pain Points
Heavy dependency weight (requires Spring, MyBatis‑Spring and several third‑party libraries).
CRUD operations rely on runtime reflection to scan entity annotations, which can become a bottleneck for massive batch jobs.
In sharding or ultra‑high‑concurrency scenarios, the reflection overhead may limit throughput.
Mybatis-Flex Overview
Design Philosophy
Mybatis-Flex focuses on performance optimization rather than feature accumulation. It is a community‑driven enhancement that adds flexible dynamic‑SQL capabilities while keeping the core MyBatis unchanged.
Core Principle – Skipping Interceptor Overhead
Flex claims 5–10× speed improvement by completely avoiding MyBatis’s Interceptor mechanism and runtime reflection. Instead of intercepting and modifying SQL, it builds the final SQL string in Java via a SqlProvider architecture.
During compilation, an APT processor scans entities annotated with @Table and generates column‑mapping constant classes, eliminating runtime reflection.
Multi‑Table Join – Native Support
QueryWrapper query = QueryWrapper.create()
.select(ACCOUNT.ID, ACCOUNT.USER_NAME, ORDER.AMOUNT.sum())
.from(ACCOUNT)
.leftJoin(ORDER).on(ACCOUNT.ID.eq(ORDER.USER_ID))
.groupBy(ACCOUNT.ID);
List<AccountVO> results = accountMapper.selectListByQuery(query);The chain‑style API offers IDE code completion and type safety without switching to XML.
Dynamic Table Name & Field Flexibility
Db.update("book_store_" + orgCode)
.set("source_code", clashVal)
.where("content_id = ?", channelId);No XML or annotation concatenation is required.
Db+Row – No‑Entity Operations
Flex’s Db+Row tool enables CRUD and pagination without defining entity classes, useful for rapid prototyping or reporting projects.
Eight‑Dimension Comparison
1. Core Design Philosophy & Underlying Mechanism
Mybatis-Plus : Non‑intrusive enhancement using MyBatis interceptors; injects SQL at startup via dynamic proxies.
Mybatis-Flex : Pure enhancement without altering MyBatis; uses compile‑time APT to generate constants and builds SQL strings directly, resulting in minimal runtime overhead.
2. Development Efficiency & Learning Curve
Mybatis-Plus : Extremely easy integration, mature ecosystem, abundant Chinese documentation, code generator for full scaffolding.
Mybatis-Flex : Similar BaseMapper inheritance and chain queries, but fewer Chinese resources; developers may need to read source code for edge cases.
3. Query Flexibility (Key Differentiator)
Mybatis-Plus : Elegant single‑table wrappers; limited multi‑table join support, often requiring XML or third‑party tools.
Mybatis-Flex : Native support for left/right/inner joins, UNION ALL, sub‑queries, over 110 SQL functions, dynamic tables and schemas – excels in complex queries.
4. Performance
Mybatis-Plus : Moderate performance; interceptor chain and runtime reflection add overhead, especially in batch or complex queries.
Mybatis-Flex : 5–10× faster in query benchmarks (e.g., fetching 10,000 records); near‑native MyBatis speed for large‑scale or high‑concurrency workloads.
5. Multi‑Database & Dialect Support
Mybatis-Plus : Good support for mainstream databases (MySQL, PostgreSQL, Oracle, SQL Server); slower adoption of Chinese domestic databases.
Mybatis-Flex : Supports >20 domestic databases (e.g., 达梦, 人大金仓, 华为高斯) in addition to mainstream ones.
6. Advanced Feature Completeness
Mybatis-Plus : Primary‑key strategies, logical delete, optimistic lock, multi‑tenant, data permission, auto‑fill, code generator; some advanced features require paid plugins.
Mybatis-Flex : Multi‑primary‑key, logical delete, optimistic lock, data fill, data masking, multi‑tenant, all free and open‑source; includes Db+Row.
7. Dependency Granularity & Intrusiveness
Mybatis-Plus : Relatively heavy; brings in spring-tx, mybatis-spring and several third‑party libs.
Mybatis-Flex : Ultra‑lightweight; only depends on MyBatis itself, reducing jar conflicts in micro‑services.
8. Community Ecosystem & Future Outlook
Mybatis-Plus : Over 15k GitHub stars, massive enterprise adoption in China, active community, stable releases.
Mybatis-Flex : Newer but rapidly growing contributors; recent updates for Spring Boot 4, modern annotations like JSpecify, strong momentum.
Practical Selection Guidance
Scenarios Favoring Mybatis-Plus
Traditional enterprise projects needing proven stability and extensive community support.
Fast‑development cases with simple single‑table CRUD and minimal join requirements.
Teams already deep‑invested in Mybatis-Plus tooling and templates.
Projects relying heavily on code generators for scaffolding.
Legacy MyBatis migrations where zero‑cost replacement is desired.
Scenarios Favoring Mybatis-Flex
Complex reporting or analytics systems with frequent multi‑table joins.
High‑concurrency, performance‑critical micro‑services where every millisecond counts.
Multi‑tenant or dynamic‑schema applications needing elegant dynamic table handling.
Projects targeting domestic databases (达梦, 人大金仓, etc.) where Flex’s dialect support simplifies integration.
Teams prioritizing minimal dependencies and lightweight architecture.
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.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
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.
