Master MyBatis‑Mate: Dictionary Binding, Encryption, Sharding & Data Scope Explained
This guide introduces MyBatis‑Mate’s core capabilities—including dictionary binding, field encryption, data masking, automatic DDL maintenance, dynamic sharding, and data‑scope permissions—while providing Maven dependencies and complete Java code examples for integrating these features into Spring Boot applications.
1. Main Features
Dictionary binding
Field encryption
Data masking
Dynamic table structure maintenance
Data audit logging
Data scope (data permission)
Database sharding, dynamic data source, read‑write separation, health‑check auto‑switch
2. Usage
2.1 Dependency Import
Add the starter and annotation packages to the Spring Boot project.
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-mate-starter</artifactId>
<version>1.0.8</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-mate-annotation</artifactId>
<version>1.0.8</version>
</dependency>2.2 Dictionary Binding
Use @FieldDict to map a dictionary type to a target property.
@FieldDict(type = "user_sex", target = "sexText")
private Integer sex;
private String sexText;Implement IDataDict to provide the dictionary data source.
@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
Annotate a field with @FieldEncrypt to store encrypted data and automatically decrypt on query. The algorithm can be configured globally or per annotation.
@FieldEncrypt(algorithm = Algorithm.PBEWithMD5AndDES)
private String password;2.4 Data Masking
Apply @FieldSensitive to mask data according to built‑in SensitiveType strategies or custom strategies.
@FieldSensitive(type = "testStrategy")
private String username;
@FieldSensitive(type = SensitiveType.mobile)
private String mobile;Register a custom strategy as a Spring bean.
@Configuration
public class SensitiveStrategyConfig {
@Bean
public ISensitiveStrategy sensitiveStrategy() {
return new SensitiveStrategy()
.addStrategy("testStrategy", t -> t + "***test***");
}
}2.5 DDL Auto Maintenance
Supports MySQL and PostgreSQL for automatic table‑structure upgrades.
@Component
public class PostgresDdl implements IDdl {
@Override
public List<String> getSqlFiles() {
return Arrays.asList("db/tag-schema.sql", "D:\\db\\tag-data.sql");
}
}Dynamic execution example:
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
Use @Sharding on mapper methods to switch between data sources.
@Mapper
@Sharding("mysql")
public interface UserMapper extends BaseMapper<User> {
@Sharding("postgres")
Long selectByUsername(String username);
}Custom sharding strategy can extend RandomShardingStrategy and override determineDatasourceKey.
@Component
public class MyShardingStrategy extends RandomShardingStrategy {
@Override
public void determineDatasourceKey(String group, Invocation invocation, SqlCommandType sqlCommandType) {
this.changeDatabaseKey(group, sqlCommandType, keys -> chooseKey(keys, invocation));
}
}2.7 Data Permission
Add @DataScope on mapper methods to enforce row‑level permissions.
@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);Provide a custom IDataScopeProvider to build the WHERE clause.
@Bean
public IDataScopeProvider dataScopeProvider() {
return new AbstractDataScopeProvider() {
@Override
protected void setWhere(PlainSelect plainSelect, Object[] args,
DataScopeProperty dataScopeProperty) {
if ("test".equals(dataScopeProperty.getType())) {
// add department IN condition and mobile LIKE condition
// (implementation omitted for brevity)
}
}
};
}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 Architecture Diary
Committed to sharing original, high‑quality technical articles; no fluff or promotional content.
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.
