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
青苗
.
Free Video Tutorials Produced by 青苗, Quality Guaranteed
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 @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 doesn't match, expected value %s actual value %s", change.getPropertyName(), change.getLeft(), change.getRight()));}}));// 2. Manual comparison callDataAuditor.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
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 for yes, false for no - Annotation @DataColumn
Property Type Required Default Description alias String No "" Associated table alias name String Yes Field 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 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:
- Automatically maintains database
Schema
initialization and upgradeSQL
scripts. Unlikeflyway
, 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.@Componentpublic class MysqlDdl implements IDdl {/*** Method to execute SQL scripts*/@Overridepublic List<String> getSqlFiles() {return Arrays.asList("db/tag-schema.sql","D:\\db\\tag-data.sql");}}// Switch to MySQL replica and execute SQL scriptsShardingKey.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
Property Type Required Default Description sharding String No "" Specifies the sharding data source type String Yes Type (used to distinguish between different businesses) target String Yes Target display property (property to bind, ensure you exclude non-database fields) - Database
sex
values0
,1
are automatically mapped toMale
,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
@Componentpublic 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
@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 call database to query role informationput("roleName", "Manager");}});}};}}
Field Encryption and Decryption
-
Usage example: 👉 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 Description MD5_32 32-bit MD5 algorithm MD5_16 16-bit MD5 algorithm BASE64 Algorithm using 64 characters to represent any binary data AES AES symmetric algorithm 【Use this algorithm if fuzzy query is required】 RSA Asymmetric encryption algorithm SM2 Chinese National Standard SM2 asymmetric encryption algorithm, based on ECC SM3 Chinese National Standard SM3 message digest algorithm, comparable to MD5 SM4 Chinese National Standard SM4 symmetric encryption algorithm, block data algorithm for WLAN standards PBEWithMD5AndDES Hybrid algorithm PBEWithMD5AndTripleDES Hybrid algorithm PBEWithHMACSHA512AndAES_256 Hybrid algorithm PBEWithSHA1AndDESede Hybrid algorithm PBEWithSHA1AndRC2_40 Hybrid algorithm -
👉 Chinese National Standard SM2.3.4 Algorithm Usage Specification
-
The
@FieldEncrypt
annotation implements data encryption and decryption, supporting multiple encryption algorithms@FieldEncryptprivate 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 includingphone number
,email
, andbank card number
.@FieldSensitive("testStrategy")private String username;@Configurationpublic class SensitiveStrategyConfig {/*** Inject desensitization strategy*/@Beanpublic ISensitiveStrategy sensitiveStrategy() {// Custom testStrategy type desensitization handlingreturn new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");}}// Skip desensitization processing for edit scenariosRequestDataTransfer.skipSensitive();
Multiple Data Source Sharding and Read-Write Separation
- Example usage: 👉 mybatis-mate-sharding
- Annotation @Sharding
Property Type Required Default Value Description value String Yes "" Sharding group name, empty uses default primary data source strategy Class No RandomShardingStrategy Sharding & table splitting strategy - Configuration
mybatis-mate:sharding:health: true # Health checkprimary: mysql # Default selected data sourcedatasource:mysql: # Database group- key: node1...- key: node2cluster: 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 node2ShardingKey.change("mysqlnode2");
Dynamic Loading and Unloading of Multiple Data Sources
- Example usage: 👉 mybatis-mate-sharding-dynamic
Multi-Data Source Transactions (JTA Atomikos)
- Example usage: 👉 mybatis-mate-sharding-jta-atomikos