Master MyBatis-Mate: Advanced Features for Secure, Sharded Java Backends

This article introduces MyBatis‑Mate, an enterprise‑grade MyBatis extension that provides sharding, data auditing, sensitive‑word filtering, field encryption, dictionary binding, dynamic DDL maintenance, data‑scope permissions and performance monitoring, complete with practical code examples and configuration guidance.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Master MyBatis-Mate: Advanced Features for Secure, Sharded Java Backends

MyBatis‑Mate is an enterprise‑level module for MyBatis that supports sharding, data auditing, sensitive‑word filtering (Aho‑Corasick algorithm), field encryption, dictionary binding (data mapping), data permissions, automatic DDL generation, and SQL maintenance, aiming to handle data more agilely and elegantly.

Main Features

Dictionary binding

Field encryption

Data masking

Dynamic table structure maintenance

Data audit records

Data scope (data permissions)

Database sharding, dynamic data source, read/write separation, health‑check auto‑switch

2. Usage

2.1 Dependency Import

<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 Field Data Binding (Dictionary Write‑Back)

For 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

Annotate a field with @FieldEncrypt to store encrypted data and automatically decrypt on query. Global and per‑annotation encryption algorithms can be configured, and custom IEncryptor implementations can be injected.

@FieldEncrypt(algorithm = Algorithm.PBEWithMD5AndDES)
private String password;

2.4 Field Masking

Use @FieldSensitive to apply predefined or custom masking strategies (e.g., name, bank account, phone number). Custom strategies can be added via Spring configuration.

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

@FieldSensitive(type = SensitiveType.mobile)
private String mobile;
@Configuration
public class SensitiveStrategyConfig {
    @Bean
    public ISensitiveStrategy sensitiveStrategy() {
        return new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");
    }
}

2.5 DDL Automatic Maintenance

Automatically generate and execute DDL scripts for MySQL and PostgreSQL during version upgrades.

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

The same approach works for MySQL, with support for dynamic execution and multi‑data‑source handling.

@Component
public class MysqlDdl implements IDdl {
    @Override
    public void sharding(Consumer<IDdl> consumer) {
        String group = "mysql";
        ShardingGroupProperty sgp = ShardingKey.getDbGroupProperty(group);
        if (sgp != null) {
            sgp.getMasterKeys().forEach(key -> {
                ShardingKey.change(group + key);
                consumer.accept(this);
            });
            sgp.getSlaveKeys().forEach(key -> {
                ShardingKey.change(group + key);
                consumer.accept(this);
            });
        }
    }

    @Override
    public List<String> getSqlFiles() {
        return Arrays.asList("db/user-mysql.sql");
    }
}

2.6 Dynamic Multi‑Data‑Source Switching

The @Sharding annotation allows free switching of data sources at mapper level.

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

2.7 Distributed Transaction Logging

A performance interceptor logs each SQL statement with execution time, optionally writing to log files and throwing exceptions when execution exceeds a configured threshold.

@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 (Data Scope)

Add @DataScope on mapper methods to enforce row‑level permissions based on department IDs, mobile numbers, etc.

// Example mapper method with data scope
@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 might look like:

SELECT u.* FROM user u
WHERE (u.department_id IN ('1','2','3','5'))
AND u.mobile LIKE '%1533%' LIMIT 1, 10

For more examples and a paid version with additional features, see the official repository:

https://gitee.com/baomidou/mybatis-mate-examples
JavadatabaseshardingMyBatisdata encryption
Java High-Performance Architecture
Written by

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.

0 followers
Reader feedback

How this landed with the community

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.