Backend Development 8 min read

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.

Java Architecture Diary
Java Architecture Diary
Java Architecture Diary
Master MyBatis‑Mate: Dictionary Binding, Encryption, Sharding & Data Scope Explained

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.

<code>&lt;dependency&gt;
  &lt;groupId&gt;com.baomidou&lt;/groupId&gt;
  &lt;artifactId&gt;mybatis-mate-starter&lt;/artifactId&gt;
  &lt;version&gt;1.0.8&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
  &lt;groupId&gt;com.baomidou&lt;/groupId&gt;
  &lt;artifactId&gt;mybatis-mate-annotation&lt;/artifactId&gt;
  &lt;version&gt;1.0.8&lt;/version&gt;
&lt;/dependency&gt;</code>

2.2 Dictionary Binding

Use

@FieldDict

to map a dictionary type to a target property.

<code>@FieldDict(type = "user_sex", target = "sexText")
private Integer sex;

private String sexText;</code>

Implement

IDataDict

to provide the dictionary data source.

<code>@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);
    }
}</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.

<code>@FieldEncrypt(algorithm = Algorithm.PBEWithMD5AndDES)
private String password;</code>

2.4 Data Masking

Apply

@FieldSensitive

to mask data according to built‑in

SensitiveType

strategies or custom strategies.

<code>@FieldSensitive(type = "testStrategy")
private String username;

@FieldSensitive(type = SensitiveType.mobile)
private String mobile;</code>

Register a custom strategy as a Spring bean.

<code>@Configuration
public class SensitiveStrategyConfig {
    @Bean
    public ISensitiveStrategy sensitiveStrategy() {
        return new SensitiveStrategy()
            .addStrategy("testStrategy", t -> t + "***test***");
    }
}</code>

2.5 DDL Auto Maintenance

Supports MySQL and PostgreSQL for automatic table‑structure upgrades.

<code>@Component
public class PostgresDdl implements IDdl {
    @Override
    public List<String> getSqlFiles() {
        return Arrays.asList("db/tag-schema.sql", "D:\\db\\tag-data.sql");
    }
}</code>

Dynamic execution example:

<code>ddlScript.run(new StringReader("DELETE FROM user;\n" +
    "INSERT INTO user (id, username, password, sex, email) VALUES\n" +
    "(20, 'Duo', '123456', 0, '[email protected]');"));</code>

2.6 Dynamic Multi‑DataSource Switching

Use

@Sharding

on mapper methods to switch between data sources.

<code>@Mapper
@Sharding("mysql")
public interface UserMapper extends BaseMapper<User> {
    @Sharding("postgres")
    Long selectByUsername(String username);
}</code>

Custom sharding strategy can extend

RandomShardingStrategy

and override

determineDatasourceKey

.

<code>@Component
public class MyShardingStrategy extends RandomShardingStrategy {
    @Override
    public void determineDatasourceKey(String group, Invocation invocation, SqlCommandType sqlCommandType) {
        this.changeDatabaseKey(group, sqlCommandType, keys -> chooseKey(keys, invocation));
    }
}</code>

2.7 Data Permission

Add

@DataScope

on mapper methods to enforce row‑level permissions.

<code>@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);
</code>

Provide a custom

IDataScopeProvider

to build the WHERE clause.

<code>@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)
            }
        }
    };
}
</code>
backendJavaShardingMyBatisdata encryptiondata maskingData Permission
Java Architecture Diary
Written by

Java Architecture Diary

Committed to sharing original, high‑quality technical articles; no fluff or promotional content.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.