Skip to content

Advanced Features

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

  • Example usage: Portal
  • Contact the author for confirmation. After publishing an introduction article about Mybatis-Mate on an official WeChat public account, you can obtain 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 responsibility of Qing Miao individually.

Data Auditing (Reconciliation)

  • Example usage: 👉 mybatis-mate-audit
  • Compare property differences between two objects, e.g., 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 mismatch, expected value %s actual value %s", change.getPropertyName(), change.getLeft(), change.getRight()));
    }
    }));
    // 2. Manual comparison
    DataAuditor.compare(obj1, obj2);

Data Sensitive Word Filtering

  • Usage Example👉 mybatis-mate-sensitive-words
  • Data sensitive word filtering (AC algorithm) automatically processes all string-sensitive word filtering in requests after configuring the handler. It supports nested keywords, leaving no room for sensitive words to hide.
  • The database maintains its own sensitive word library (free and controllable). By default, cached word roots are loaded, and the word library can be reloaded on demand.

Data Scope (Data Permission)

  • Example usage: 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: yes, false: no)
  • Annotation @DataColumn
    PropertyTypeRequiredDefaultDescription
    aliasStringNo""Associated table alias
    nameStringYesField name
  • Row-level granular permission control, e.g., a parent department can view sub-department information.
    // Testing test-type data permission scope with mixed pagination mode
    @DataScope(type = "test", value = {
    // Associated table user alias u specifying department field permission
    @DataColumn(alias = "u", name = "department_id"),
    // Associated table user alias u specifying 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);
    // Testing data permission, 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:
  • Database Schema initialization and SQL upgrade auto-maintenance. Unlike flyway, it supports sharding databases/tables and allows controlled execution of SQL scripts via code.
  • On the first run, a ddl_history table will be created in the database, and version information will be automatically maintained for each executed SQL script.
    @Component
    public class MysqlDdl implements IDdl {
    /**
    * Method for executing SQL scripts
    */
    @Override
    public List<String> getSqlFiles() {
    return Arrays.asList(
    "db/tag-schema.sql",
    "D:\\db\\tag-data.sql"
    );
    }
    }
    // Switch to the MySQL secondary database and execute the SQL script
    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)

  • Example: 👉 mybatis-mate-dict
  • Annotation @FieldBind
    PropertyTypeRequiredDefaultDescription
    shardingStringNo""Specifies the sharding data source
    typeStringYesType (used to distinguish different businesses)
    targetStringYesTarget display property (property to be bound, ensure non-database fields are excluded)
  • Database sex values 0, 1 are automatically mapped to Male, Female
  • Can be bound and mapped to an object, e.g., mapping an order ID to an order object or number
    @FieldBind(type = "user_sex", target = "sexText")
    private Integer sex;
    // Bound display property, non-table dictionary (excluded)
    @TableField(exist = false)
    private String sexText;
  • The binding business handler class must implement the IDataBind interface and be injected into the Spring container
    @Component
    public class DataBind implements IDataBind {
    ...
    }

Virtual Attribute Binding

  • Example: 👉 mybatis-mate-jsonbind
  • Annotation @JsonBind
    @JsonBind("bindingType")
    public class User {
    ...
    }
  • Return Json virtual attribute 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 query role information from the database
    put("roleName", "Manager");
    }});
    }
    };
    }
    }

Field Encryption and Decryption

  • Example usage: 👉 mybatis-mate-encrypt

  • Annotation @FieldEncrypt

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

    AlgorithmDescription
    MD5_3232-bit MD5 algorithm
    MD5_1616-bit MD5 algorithm
    BASE64Algorithm representing arbitrary binary data with 64 characters
    AESAES symmetric algorithm 【Must use this algorithm for fuzzy queries】
    RSAAsymmetric encryption algorithm
    SM2National SM2 asymmetric encryption algorithm, based on ECC
    SM3National SM3 message digest algorithm, comparable to MD5
    SM4National SM4 symmetric encryption algorithm, a block data algorithm for WLAN standards
    PBEWithMD5AndDESHybrid algorithm
    PBEWithMD5AndTripleDESHybrid algorithm
    PBEWithHMACSHA512AndAES_256Hybrid algorithm
    PBEWithSHA1AndDESedeHybrid algorithm
    PBEWithSHA1AndRC2_40Hybrid algorithm
  • 👉 National SM2.3.4 Algorithm Usage Specification

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

    @FieldEncrypt
    private String email;

Field Desensitization

  • Example usage: 👉 mybatis-mate-sensitive-jackson
  • Annotation @FieldSensitive
  • The FieldSensitive annotation implements data desensitization, with built-in 9 common desensitization rules such as phone number, email, and bank card number.
    @FieldSensitive("testStrategy")
    private String username;
    @Configuration
    public class SensitiveStrategyConfig {
    /**
    * Inject desensitization strategy
    */
    @Bean
    public ISensitiveStrategy sensitiveStrategy() {
    // Custom desensitization handling for the "testStrategy" type
    return new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");
    }
    }
    // Skip desensitization processing for editing scenarios
    RequestDataTransfer.skipSensitive();

Multiple Data Sources Sharding (Read-Write Separation)

  • Example usage: 👉 mybatis-mate-sharding
  • Annotation @Sharding
    AttributeTypeRequiredDefault ValueDescription
    valueStringYes""Sharding group name, empty uses default primary data source
    strategyClassNoRandomShardingStrategySharding & Table 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 # In read-write separation, slave nodes handle SQL queries (master nodes default to "master" if unspecified)
    ...
    postgres:
    - key: node1 # Data node
    ...
  • Use @Sharding annotation to switch data sources (random selection within group by default, read from slave and write to master)
    @Mapper
    @Sharding("mysql")
    public interface UserMapper extends BaseMapper<User> {
    @Sharding("postgres")
    Long selectByUsername(String username);
    }
  • Switch to a specified database node
    // Switch to mysql slave node2
    ShardingKey.change("mysqlnode2");

Dynamic Loading and Unloading of Multiple Data Sources

Multi-DataSource Transactions (JTA Atomikos)

Baomidou

© 2016-2025 Baomidou™. All Rights Reserved.

Power by Astro Starlight | Sponsored by JetBrains

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