Master Dynamic Table Names in MyBatis‑Plus with a Simple Starter
This article introduces an open‑source MyBatis‑Plus dynamic‑table starter, explains why dynamic table names are needed for large‑scale data, outlines its key features, provides step‑by‑step installation and quick‑start instructions, demonstrates advanced usage, debugging tips, FAQs, and real‑world scenarios.
Introduction
This guide presents an open‑source MyBatis‑Plus Dynamic Table Name Starter that focuses on a "simple, stable, and extensible" approach to table sharding. The starter reduces the complexity of dynamic table handling to a minimum, allowing developers to implement sharding in about ten minutes.
Why Dynamic Table Names?
As data volume grows, sharding tables by time or user becomes common. Traditional implementations often involve manual SQL concatenation, interceptor modifications, strategy maintenance, and extensive regression testing, which are costly and error‑prone. The starter uses @DateSharding and @HashSharding annotations combined with configuration to minimize these pains.
Zero‑intrusion, ready‑to‑use.
Annotation‑driven CRUD‑like business code.
Strategy pattern enables easy custom sharding logic.
Comprehensive logging for troubleshooting.
Key Features
Out‑of‑the‑box: Auto‑configuration, enabled by default.
Date sharding: Switch between yearly, monthly, or daily tables with a single click.
Hash sharding: Evenly distribute data across a configurable number of tables.
Annotation driven: Use @DateSharding and @HashSharding directly on service methods.
Utility support: DynamicTableUtils can wrap any code block.
Flexible priority: Multiple strategies coexist with controllable precedence.
Full logging: Trace strategy matching and table‑name replacement steps.
Installation
Add the starter as a Maven or Gradle dependency (Java 21+, Spring Boot 3.5.6+, MyBatis‑Plus 3.5.14+ required).
<dependency>
<groupId>com.lizhuolun</groupId>
<artifactId>mybatis-plus-dynamic-table-starter</artifactId>
<version>1.0.0</version>
</dependency> implementation 'com.lizhuolun:mybatis-plus-dynamic-table-starter:1.0.0'Quick Start (3 Steps)
Add the dependency and ensure Spring Web and MyBatis‑Plus starters are present.
Configure sharding strategy in application.yml.
# Dynamic table configuration
dynamic-table:
enabled: true
enable-sql-log: true
# Date sharding example (monthly order table)
date-sharding:
- tables: [t_order, t_log]
date-pattern: "yyyyMM"
priority: 1
- tables: [t_access_log]
date-pattern: "yyyyMMdd"
priority: 2
# Hash sharding example (8 tables for user data)
hash-sharding:
- tables: [t_user, t_user_profile]
table-count: 8
priority: 10Use the annotations or utility in code.
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
// Automatic date‑based sharding, e.g., t_order_202501
@DateSharding(value = "t_order", dateParam = "date")
public Order create(Order order, LocalDate date) {
orderMapper.insert(order);
return order;
}
}
// Utility‑based approach
public List<Order> queryByDate(LocalDate date) {
return DynamicTableUtils.executeWithDate("t_order", date, () -> {
return orderMapper.selectList(null);
});
}Advanced Usage
Multiple tables routing: Map logical tables to actual sharded tables in a single call.
Map<String, String> tableMap = Map.of(
"t_order", "t_order_202501",
"t_log", "t_log_202501"
);
DynamicTableUtils.executeWithTables(tableMap, () -> {
orderMapper.insert(order);
logMapper.insert(log);
});Custom strategy: Implement TableRouterStrategy to plug in your own routing rules.
@Component
public class CustomTableRouterStrategy implements TableRouterStrategy {
@Override
public boolean match(String logicTableName) {
return "t_custom".equals(logicTableName);
}
@Override
public String getActualTableName(String logic, Object ctx) {
return logic + "_" + suffix(ctx);
}
@Override
public String getStrategyName() {
return "CustomTableRouterStrategy";
}
@Override
public int getPriority() {
return 100;
}
}Debugging & Performance
Enable detailed logging to locate table‑name replacement:
dynamic-table:
enable-sql-log: true
logging:
level:
com.lizhuolun.mybatis.dynamic: DEBUGRecommended connection pool (HikariCP) settings:
spring:
datasource:
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000FAQ
Table name not replaced – verify the tables list, strategy matching, and that logging is enabled.
Strategy not effective – ensure annotation parameters ( dateParam, hashKey) match method arguments and that AOP is functioning.
SQL errors – confirm the actual sharded tables exist and share the same schema; check logs for replacement results.
Applicable Scenarios
Business archiving: Orders or logs grow over time; monthly/daily tables speed up queries.
User sharding: Distribute write/read load across user‑based partitions.
Comparison with custom interceptors: This starter is lighter, configuration‑driven, and easier to maintain.
Demo & Quick Verification
Clone the demo repository mybatis-plus-dynamic-table-demo, initialize the database per the README, and run: mvn spring-boot:run Use curl or Postman to call the sample endpoints and observe SQL replacement and sharding effects.
Roadmap
More strategy templates and expression support.
Richer examples and best‑practice guides.
Production troubleshooting guides and gray‑release solutions.
Ecosystem & Compatibility
Supported runtime: Java 21+, Spring Boot 3.5.6+, MyBatis‑Plus 3.5.14+.
License: Apache‑2.0.
Contributions welcome via Issues and Pull Requests (see repository CONTRIBUTING guide).
Project repository (starter): https://github.com/sxhjlzl/mybatis-plus-dynamic-table-starter
Demo repository: https://github.com/sxhjlzl//mybatis-plus-dynamic-table-demo
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.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.
