Unlock Enterprise-Level Data Management with MyBatis-Mate: Sharding, Encryption, and Dynamic DDL
mybatis-mate extends MyBatis with enterprise-grade capabilities such as sharding, multi-datasource routing, data audit, sensitive-word filtering, field encryption, dictionary binding, dynamic DDL generation, data-scope permissions, and performance logging, providing a comprehensive solution for agile and secure data handling in Java backend applications.
Introduction
mybatis-mate is an enterprise-level module for MyBatis, supporting sharding, data audit, sensitive word filtering (Aho-Corasick), field encryption, dictionary binding, data permission, automatic table DDL maintenance, and more, aiming to handle data more agilely and elegantly.
Main Features
Dictionary binding
Field encryption
Data desensitization
Dynamic table structure maintenance
Data audit records
Data scope (data permission)
Database sharding, dynamic data source, read/write separation, automatic health‑check switching
2. Usage
2.1 Dependency Import
Spring Boot starter dependency:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-mate-starter</artifactId>
<version>1.0.8</version>
</dependency>Annotation package (for entity sub‑packages):
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-mate-annotation</artifactId>
<version>1.0.8</version>
</dependency>2.2 Field Data Binding (Dictionary Write‑Back)
Example: map the "sex" dictionary to the sexText property.
@FieldDict(type = "user_sex", target = "sexText")
private Integer sex;
private String sexText;Implement IDataDict to provide dictionary data and inject it into the Spring container.
@Component
public class DataDict implements IDataDict {
private Map<String, String> SEX_MAP = new ConcurrentHashMap<String, String>() {{
put("0", "女");
put("1", "男");
}};
@Override
public String getNameByCode(FieldDict fieldDict, String code) {
System.err.println("字段类型:" + fieldDict.type() + ",编码:" + code);
return SEX_MAP.get(code);
}
}2.3 Field Encryption
Use @FieldEncrypt to encrypt stored values; decryption occurs automatically on query. Global and per‑field algorithms can be configured, and custom encryptors can be injected via IEncryptor.
@FieldEncrypt(algorithm = Algorithm.PBEWithMD5AndDES)
private String password;2.4 Field Desensitization
Apply @FieldSensitive to automatically mask data according to predefined strategies (9 built‑in types) such as Chinese names, bank cards, phone numbers, etc. Custom strategies can also be defined.
@FieldSensitive(type = "testStrategy")
private String username;
@FieldSensitive(type = SensitiveType.mobile)
private String mobile;Register the custom strategy in a Spring configuration:
@Configuration
public class SensitiveStrategyConfig {
@Bean
public ISensitiveStrategy sensitiveStrategy() {
return new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");
}
}2.5 Automatic DDL Maintenance
Handles table structure upgrades and versioned SQL maintenance for MySQL and PostgreSQL.
@Component
public class PostgresDdl implements IDdl {
@Override
public List<String> getSqlFiles() {
return Arrays.asList(
"db/tag-schema.sql",
"D:\\db\\tag-data.sql"
);
}
}DDL scripts can be executed statically or dynamically:
ddlScript.run(new StringReader(
"DELETE FROM user;
" +
"INSERT INTO user (id, username, password, sex, email) VALUES
" +
"(20, 'Duo', '123456', 0, '[email protected]');"
));2.6 Dynamic Multi‑DataSource Switching
The @Sharding annotation enables free switching of data sources at mapper level.
@Mapper
@Sharding("mysql")
public interface UserMapper extends BaseMapper<User> {
@Sharding("postgres")
Long selectByUsername(String username);
}Custom sharding strategies can be defined, e.g. extending RandomShardingStrategy to decide the datasource key.
@Component
public class MyShardingStrategy extends RandomShardingStrategy {
@Override
public void determineDatasourceKey(String group, Invocation invocation, SqlCommandType sqlCommandType) {
this.changeDatabaseKey(group, sqlCommandType, keys -> chooseKey(keys, invocation));
}
}Configuration example (health check enabled, primary datasource, node definitions):
mybatis-mate:
sharding:
health: true
primary: mysql
datasource:
mysql:
- key: node1
- key: node2
cluster: slave
postgres:
- key: node12.7 Distributed Transaction Log Printing
Performance interceptor logs each SQL statement with execution time and can enforce a maximum duration.
@Slf4j
@Component
@Intercepts({
@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
@Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
public class PerformanceInterceptor implements Interceptor {
private long maxTime = 0;
private boolean format = false;
private boolean writeInLog = false;
// ... implementation omitted for brevity ...
}2.8 Data Permission
Add @DataScope on mapper methods to apply row‑level filters.
// Example data‑scope annotation
@DataScope(type = "test", value = {
@DataColumn(alias = "u", name = "department_id"),
@DataColumn(alias = "u", name = "mobile")
})
@Select("select u.* from user u")
List<User> selectTestList(IPage<User> page, Long id, @Param("name") String username);The generated SQL will include department IN clause and mobile LIKE clause.
SELECT u.* FROM user u
WHERE (u.department_id IN ('1','2','3','5'))
AND u.mobile LIKE '%1533%' LIMIT 1, 10Only the paid version is currently available; see the mybatis‑mate examples for more usage details.
https://gitee.com/baomidou/mybatis-mate-examples
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 High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
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.
