Skip to content

Advanced Features

Mybatis-Mate is an enterprise-level module for MyBatis-Plus, designed to handle data more efficiently and elegantly.

  • Example Usage: Portal
  • Contact the author for confirmation. If you publish an introductory article about Mybatis-Mate on your official WeChat account, you can receive a free permanent personal license certificate.
  • This module is an extension library for MyBatis-Plus, not a paid version of MyBatis-Plus. Any issues are the sole responsibility of 青苗.

Data Auditing (Reconciliation)

  • Usage example: 👉 mybatis-mate-audit
  • Compare property differences between two objects, for example: bank statement reconciliation.
    // 1. Asynchronous callback, note: enable async with @EnableAsync
    applicationEventPublisher.publishEvent(new DataAuditEvent((t) -> {
    List<Change> changes = t.apply(newVersion, oldVersion);
    for (Change valueChange : changes) {
    ValueChange change = (ValueChange) valueChange;
    System.err.println(String.format("%s doesn't match, expected value %s actual value %s", change.getPropertyName(), change.getLeft(), change.getRight()));
    }
    }));
    // 2. Manual comparison call
    DataAuditor.compare(obj1, obj2);

Data Sensitive Word Filtering

  • Example Usage 👉 mybatis-mate-sensitive-words
  • After configuring the processor for data sensitive word filtering (AC algorithm), the framework automatically filters sensitive words in all requested strings. It supports nested keywords, leaving no place for sensitive words to hide.
  • The database maintains its own sensitive word library (free, controllable). By default, it loads cached word roots and supports specifying when to reload the word library.

Data Scope (Data Permissions)

  • Usage example: mybatis-mate-datascope
  • Annotation @DataScope
    PropertyTypeRequiredDefaultDescription
    typeStringNo""Scope type, used to distinguish business categories, empty by default
    valueDataColumn[]NoData permission fields, supports multi-field combinations
    ignorebooleanNofalseIgnore permission processing logic true for yes, false for no
  • Annotation @DataColumn
    PropertyTypeRequiredDefaultDescription
    aliasStringNo""Associated table alias
    nameStringYesField name
  • Row-level granular permission control, for example: a parent department can view sub-department information.
    // Test data permission scope of type 'test', mixed pagination mode
    @DataScope(type = "test", value = {
    // Associate table user alias u to specify department field permissions
    @DataColumn(alias = "u", name = "department_id"),
    // Associate table user alias u to specify mobile field (handle as needed)
    @DataColumn(alias = "u", name = "mobile")
    })
    @Select("select u.* from user u")
    List<User> selectTestList(IPage<User> page, Long id, @Param("name") String username);
    // Test data permissions, final executed SQL statement
    SELECT u.* FROM user u WHERE (u.department_id IN ('1', '2', '3', '5')) AND u.mobile LIKE '%1533%' LIMIT 1,10

Automatic Table Structure Maintenance

  • Usage examples:
  • Automatically maintains database Schema initialization and upgrade SQL scripts. Unlike flyway, it supports sharded databases and allows you to control SQL script execution through code.
  • On first run, it creates a ddl_history table in your database and automatically maintains version information each time SQL scripts are executed.
    @Component
    public class MysqlDdl implements IDdl {
    /**
    * Method to execute SQL scripts
    */
    @Override
    public List<String> getSqlFiles() {
    return Arrays.asList(
    "db/tag-schema.sql",
    "D:\\db\\tag-data.sql"
    );
    }
    }
    // Switch to MySQL replica and execute SQL scripts
    ShardingKey.change("mysqlt2");
    ddlScript.run(new StringReader("DELETE FROM user;\n" +
    "INSERT INTO user (id, username, password, sex, email) VALUES\n" +
    "(20, 'Duo', '123456', 0, 'Duo@baomidou.com');"));

Field Data Binding (Dictionary Write-Back)

  • Usage example: 👉 mybatis-mate-dict
  • Annotation @FieldBind
    PropertyTypeRequiredDefaultDescription
    shardingStringNo""Specifies the sharding data source
    typeStringYesType (used to distinguish between different businesses)
    targetStringYesTarget display property (property to bind, ensure you exclude non-database fields)
  • Database sex values 0, 1 are automatically mapped to Male, Female
  • You can bind and map to an object, for example: map to an order object or number based on the order ID
    @FieldBind(type = "user_sex", target = "sexText")
    private Integer sex;
    // Bind display property, non-table dictionary (excluded)
    @TableField(exist = false)
    private String sexText;
  • The binding business handler class needs to implement the IDataBind interface and be injected into the Spring container
    @Component
    public class DataBind implements IDataBind {
    ...
    }

Virtual Property Binding

  • Usage example: 👉 mybatis-mate-jsonbind
  • Annotation @JsonBind
    @JsonBind("bindingType")
    public class User {
    ...
    }
  • Return JSON virtual property binding strategy
    @Component
    public class JsonBindStrategy implements IJsonBindStrategy {
    @Override
    public Map<String, Function<Object, Map<String, Object>>> getStrategyFunctionMap() {
    return new HashMap<String, Function<Object, Map<String, Object>>>(16) {
    {
    // Inject virtual nodes
    put(Type.departmentRole, (obj) -> new HashMap(2) {{
    User user = (User) obj;
    // Enum type conversion
    put("statusText", StatusEnum.get(user.getStatus()).getDesc());
    // Can call database to query role information
    put("roleName", "Manager");
    }});
    }
    };
    }
    }

Field Encryption and Decryption

  • Usage example: 👉 mybatis-mate-encrypt

  • Annotation @FieldEncrypt

    AttributeTypeRequiredDefault ValueDescription
    passwordStringNo""Encryption password
    algorithmAlgorithmNoPBEWithMD5AndDESPBE MD5 DES hybrid algorithm
    encryptorClassNoIEncryptorEncryption processor
  • Algorithm

    AlgorithmDescription
    MD5_3232-bit MD5 algorithm
    MD5_1616-bit MD5 algorithm
    BASE64Algorithm using 64 characters to represent any binary data
    AESAES symmetric algorithm 【Use this algorithm if fuzzy query is required】
    RSAAsymmetric encryption algorithm
    SM2Chinese National Standard SM2 asymmetric encryption algorithm, based on ECC
    SM3Chinese National Standard SM3 message digest algorithm, comparable to MD5
    SM4Chinese National Standard SM4 symmetric encryption algorithm, block data algorithm for WLAN standards
    PBEWithMD5AndDESHybrid algorithm
    PBEWithMD5AndTripleDESHybrid algorithm
    PBEWithHMACSHA512AndAES_256Hybrid algorithm
    PBEWithSHA1AndDESedeHybrid algorithm
    PBEWithSHA1AndRC2_40Hybrid algorithm
  • 👉 Chinese National Standard SM2.3.4 Algorithm Usage Specification

  • The @FieldEncrypt annotation implements data encryption and decryption, supporting multiple encryption algorithms

    @FieldEncrypt
    private String email;

Field Desensitization

  • Usage example: 👉 mybatis-mate-sensitive-jackson

  • Annotation @FieldSensitive

  • The @FieldSensitive annotation implements data desensitization with 9 built-in common desensitization rules including phone number, email, and bank card number.

    @FieldSensitive("testStrategy")
    private String username;
    @Configuration
    public class SensitiveStrategyConfig {
    /**
    * Inject desensitization strategy
    */
    @Bean
    public ISensitiveStrategy sensitiveStrategy() {
    // Custom testStrategy type desensitization handling
    return new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");
    }
    }
    // Skip desensitization processing for edit scenarios
    RequestDataTransfer.skipSensitive();

Multiple Data Source Sharding and Read-Write Separation

  • Example usage: 👉 mybatis-mate-sharding
  • Annotation @Sharding
    PropertyTypeRequiredDefault ValueDescription
    valueStringYes""Sharding group name, empty uses default primary data source
    strategyClassNoRandomShardingStrategySharding & table splitting strategy
  • Configuration
    mybatis-mate:
    sharding:
    health: true # Health check
    primary: mysql # Default selected data source
    datasource:
    mysql: # Database group
    - key: node1
    ...
    - key: node2
    cluster: slave # Handles SQL query operations during read-write separation, master cluster defaults to not writing
    ...
    postgres:
    - key: node1 # Data node
    ...
  • Use the @Sharding annotation to switch data sources, with nodes within the group randomly selected by default (read from slave, write to master)
    @Mapper
    @Sharding("mysql")
    public interface UserMapper extends BaseMapper<User> {
    @Sharding("postgres")
    Long selectByUsername(String username);
    }
  • Switch to a specific database node
    // Switch to mysql slave node2
    ShardingKey.change("mysqlnode2");

Dynamic Loading and Unloading of Multiple Data Sources

Multi-Data Source Transactions (JTA Atomikos)

Baomidou

© 2016-2025 Baomidou™. All Rights Reserved.

Power by Astro Starlight | Sponsored by JetBrains

渝ICP备2021000141号-1 | 渝公网安备50011302222097