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.
Free Video Tutorials Produced by Qing Miao, quality guaranteed
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 @EnableAsyncapplicationEventPublisher.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 comparisonDataAuditor.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
Property Type Required Default Description type String No "" Scope type, used to distinguish business categories, empty by default value DataColumn[] No Data permission fields, supports multi-field combinations ignore boolean No false Ignore permission processing logic (true: yes, false: no) - Annotation @DataColumn
Property Type Required Default Description alias String No "" Associated table alias name String Yes Field 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 statementSELECT 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 andSQL
upgrade auto-maintenance. Unlikeflyway
, 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.@Componentpublic class MysqlDdl implements IDdl {/*** Method for executing SQL scripts*/@Overridepublic 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 scriptShardingKey.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
Property Type Required Default Description sharding String No "" Specifies the sharding data source type String Yes Type (used to distinguish different businesses) target String Yes Target display property (property to be bound, ensure non-database fields are excluded) - Database
sex
values0
,1
are automatically mapped toMale
,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@Componentpublic class DataBind implements IDataBind {...}
Virtual Attribute Binding
- Example: 👉 mybatis-mate-jsonbind
- Annotation
@JsonBind
@JsonBind("bindingType")public class User {...} - Return Json virtual attribute binding strategy
@Componentpublic class JsonBindStrategy implements IJsonBindStrategy {@Overridepublic Map<String, Function<Object, Map<String, Object>>> getStrategyFunctionMap() {return new HashMap<String, Function<Object, Map<String, Object>>>(16) {{// Inject virtual nodesput(Type.departmentRole, (obj) -> new HashMap(2) {{User user = (User) obj;// Enum type conversionput("statusText", StatusEnum.get(user.getStatus()).getDesc());// Can query role information from the databaseput("roleName", "Manager");}});}};}}
Field Encryption and Decryption
-
Example usage: 👉 mybatis-mate-encrypt
-
Annotation
@FieldEncrypt
Attribute Type Required Default Value Description password String No "" Encryption password algorithm Algorithm No PBEWithMD5AndDES PBE MD5 DES hybrid algorithm encryptor Class No IEncryptor Encryption processor -
Algorithm
Algorithm
Algorithm Description MD5_32 32-bit MD5 algorithm MD5_16 16-bit MD5 algorithm BASE64 Algorithm representing arbitrary binary data with 64 characters AES AES symmetric algorithm 【Must use this algorithm for fuzzy queries】 RSA Asymmetric encryption algorithm SM2 National SM2 asymmetric encryption algorithm, based on ECC SM3 National SM3 message digest algorithm, comparable to MD5 SM4 National SM4 symmetric encryption algorithm, a block data algorithm for WLAN standards PBEWithMD5AndDES Hybrid algorithm PBEWithMD5AndTripleDES Hybrid algorithm PBEWithHMACSHA512AndAES_256 Hybrid algorithm PBEWithSHA1AndDESede Hybrid algorithm PBEWithSHA1AndRC2_40 Hybrid algorithm -
The
@FieldEncrypt
annotation enables data encryption and decryption, supporting multiple encryption algorithms.@FieldEncryptprivate 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 asphone number
,email
, andbank card number
.@FieldSensitive("testStrategy")private String username;@Configurationpublic class SensitiveStrategyConfig {/*** Inject desensitization strategy*/@Beanpublic ISensitiveStrategy sensitiveStrategy() {// Custom desensitization handling for the "testStrategy" typereturn new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");}}// Skip desensitization processing for editing scenariosRequestDataTransfer.skipSensitive();
Multiple Data Sources Sharding (Read-Write Separation)
- Example usage: 👉 mybatis-mate-sharding
- Annotation @Sharding
Attribute Type Required Default Value Description value String Yes "" Sharding group name, empty uses default primary data source strategy Class No RandomShardingStrategy Sharding & Table strategy - Configuration
mybatis-mate:sharding:health: true # Health checkprimary: mysql # Default selected data sourcedatasource:mysql: # Database group- key: node1...- key: node2cluster: 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 node2ShardingKey.change("mysqlnode2");
Dynamic Loading and Unloading of Multiple Data Sources
- Usage example: 👉 mybatis-mate-sharding-dynamic
Multi-DataSource Transactions (JTA Atomikos)
- Example usage: 👉 mybatis-mate-sharding-jta-atomikos