Master MyBatis with Mybatis-Mate: Sharding, Encryption, Auditing and More

This article introduces Mybatis-Mate, an enterprise‑level MyBatis extension that provides sharding, data audit, sensitive‑word filtering, field encryption, dictionary binding, data permission, dynamic DDL generation and other features, and shows how to integrate and use them with practical code examples.

Programmer DD
Programmer DD
Programmer DD
Master MyBatis with Mybatis-Mate: Sharding, Encryption, Auditing and More

mybatis-mate is an enterprise‑level module for MyBatis that supports sharding, data audit, sensitive‑word filtering (Aho‑Corasick), field encryption, dictionary binding, data permission, automatic table DDL generation, and other capabilities, 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, health‑check auto‑switch

Usage

1. Dependency Import

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-mate-starter</artifactId>
  <version>1.0.8</version>
</dependency>

2. Field Dictionary Binding

Example: map user_sex dictionary to sexText property.

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

private String sexText;

Implement IDataDict and register as a Spring component to provide dictionary data.

@Component
public class DataDict implements IDataDict {
    private Map<String, String> SEX_MAP = new ConcurrentHashMap<>() {{
        put("0", "女");
        put("1", "男");
    }};

    @Override
    public String getNameByCode(FieldDict fieldDict, String code) {
        System.err.println("字段类型:" + fieldDict.type() + ",编码:" + code);
        return SEX_MAP.get(code);
    }
}

3. Field Encryption

Annotate with @FieldEncrypt to encrypt storage and automatically decrypt on query. Global and annotation‑level algorithms can be configured, and custom IEncryptor can be injected.

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

4. Data Desensitization

Use @FieldSensitive to apply built‑in or custom strategies (e.g., mobile number, Chinese name, bank card).

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

@FieldSensitive(type = SensitiveType.mobile)
private String mobile;

Custom strategy can be added via a Spring @Configuration bean.

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

5. Sensitive Word Filtering

Example controller demonstrates adding and testing sensitive words.

@RestController
public class ArticleController {
    @Autowired
    private SensitiveWordsMapper sensitiveWordsMapper;

    @GetMapping("/info")
    public String info(Article article) throws Exception {
        return ParamsConfig.toJson(article);
    }

    @GetMapping("/add")
    public String add() throws Exception {
        Long id = 3L;
        if (null == sensitiveWordsMapper.selectById(id)) {
            System.err.println("插入一个敏感词:" +
                sensitiveWordsMapper.insert(new SensitiveWords(id, "猫")));
            SensitiveWordsProcessor.reloadSensitiveWords();
        }
        return "ok";
    }
}

6. Dynamic DDL Maintenance

Implement IDdl for MySQL or PostgreSQL to provide SQL files or script execution.

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

7. Sharding and Multi‑Data‑Source Switching

Use @Sharding on mapper methods or classes to specify the target datasource group.

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

8. Data Permission

Annotate mapper methods with @DataScope and @DataColumn 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);

Configuration for sharding, health check, and datasource groups is defined in the mybatis-mate.yml file (example omitted for brevity).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentshardingMyBatisdata encryptionData Auditing
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

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.