### Spring Boot MyBatis-Plus Configuration Source: https://mybatis.plus/config Example of MyBatis-Plus configuration in a Spring Boot application using application.properties or application.yml. ```yaml mybatis-plus: ...... configuration: ...... global-config: ...... db-config: ...... ``` -------------------------------- ### Spring MVC MyBatis-Plus Configuration Source: https://mybatis.plus/config Example of configuring MyBatis-Plus in a Spring MVC application using XML bean definitions. ```xml ...... ...... ...... ...... ``` -------------------------------- ### MyBatis-Plus Global Configuration Source: https://mybatis.plus/guide/building-the-database-layer-of-a-high-concurrency-online-gambling-platform-using-mybatis-plus Configures MyBatis-Plus interceptors for features like optimistic locking and pagination. This setup is essential for enabling these functionalities across the application. ```java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor interceptor() { MybatisPlusInterceptor i = new MybatisPlusInterceptor(); i.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 乐观锁 i.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 分页 return i; } } ``` -------------------------------- ### Provide Encryption Key via Jar Startup Argument Source: https://mybatis.plus/guide/safety.html Pass the encryption key as a startup argument to your Jar file using the '--mpw.key=' format. This can also be set as a startup environment variable on servers. ```bash --mpw.key=d1104d7c3b616f0b ``` -------------------------------- ### Configure p6spy Datasource in application.yml Source: https://mybatis.plus/guide/p6spy.html Set the datasource driver class name and URL to use p6spy for logging SQL statements. ```yaml spring: datasource: driver-class-name: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:h2:mem:test ... ``` -------------------------------- ### XML Mapper for Custom Pagination Method Source: https://mybatis.plus/guide/interceptor-pagination.html The XML mapper configuration for a custom pagination method. Ensure the SQL query selects the necessary fields. ```xml ``` -------------------------------- ### Configure spy.properties for p6spy Source: https://mybatis.plus/guide/p6spy.html Customize p6spy logging behavior, including module list, log format, appender, and exclusion categories. ```properties #3.2.1以上使用 modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory #3.2.1以下使用或者不配置 #modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory # 自定义日志打印 logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger #日志输出到控制台 appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger # 使用日志系统记录 sql #appender=com.p6spy.engine.spy.appender.Slf4JLogger # 设置 p6spy driver 代理 deregisterdrivers=true # 取消JDBC URL前缀 useprefix=true # 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset. excludecategories=info,debug,result,commit,resultset # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 实际驱动可多个 #driverlist=org.h2.Driver # 是否开启慢SQL记录 outagedetection=true # 慢SQL记录标准 2 秒 outagedetectioninterval=2 ``` -------------------------------- ### Generate and Use AES Key for Encryption Source: https://mybatis.plus/guide/safety.html Generate a 16-bit random AES key using AES.generateRandomKey() and then use AES.encrypt() to encrypt your data. The generated random key must be securely managed. ```java // Generate 16位随机AES密钥 String randomKey = AES.generateRandomKey(); // 随机密钥加密 String result = AES.encrypt(data, randomKey); ``` -------------------------------- ### Configure Encrypted Database Credentials in YML Source: https://mybatis.plus/guide/safety.html Use the 'mpw:' prefix for encrypted values in your YML configuration for database URL, password, and username. Ensure the key used for encryption is kept secure. ```yaml spring: datasource: url: mpw:qRhvCwF4GOqjessEB3G+a5okP+uXXr96wcucn2Pev6Bf1oEMZ1gVpPPhdDmjQqoM password: mpw:Hzy5iliJbwDHhjLs1L0j6w== username: mpw:Xb+EgsyuYRXw7U7sBJjBpA== ``` -------------------------------- ### Mybatis-config.xml Configuration for MybatisPlusInterceptor Source: https://mybatis.plus/guide/interceptor.html Configure MybatisPlusInterceptor with PaginationInnerInterceptor in mybatis-config.xml. ```xml ``` -------------------------------- ### Add p6spy Gradle Dependency Source: https://mybatis.plus/guide/p6spy.html Include the p6spy dependency in your Gradle project to enable SQL logging. ```gradle compile group: 'p6spy', name: 'p6spy', version: '最新版本' ``` -------------------------------- ### MyBatis Configuration - Auto Mapping Unknown Column Behavior Source: https://mybatis.plus/config Specifies how MyBatis handles unknown columns or properties during automatic mapping. Options include NONE (no action), WARNING (log warnings), and FAILING (throw an exception). ```properties autoMappingUnknownColumnBehavior=NONE ``` -------------------------------- ### Add p6spy Maven Dependency Source: https://mybatis.plus/guide/p6spy.html Include the p6spy dependency in your Maven project to enable SQL logging. ```xml p6spy p6spy 最新版本 ``` -------------------------------- ### Paginated Query Template in MyBatis-Plus Source: https://mybatis.plus/guide/building-the-database-layer-of-a-high-concurrency-online-gambling-platform-using-mybatis-plus Provides a template for performing paginated queries using MyBatis-Plus's lambda query builder. It includes ordering and avoids deep pagination issues by using standard page parameters. ```java public IPage pageOrders(Long userId, long pageNo, long pageSize) { Page p = new Page<>(pageNo, pageSize); return lambdaQuery() .eq(BetOrder::getUserId, userId) .orderByDesc(BetOrder::getCreatedAt) .page(p); } ``` -------------------------------- ### Spring Boot Configuration for MybatisPlusInterceptor Source: https://mybatis.plus/guide/interceptor.html Configure MybatisPlusInterceptor with PaginationInnerInterceptor in a Spring Boot application using Java configuration. ```java @Configuration @MapperScan("scan.your.mapper.package") public class MybatisPlusConfig { /** * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除) */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2)); return interceptor; } @Bean public ConfigurationCustomizer configurationCustomizer() { return configuration -> configuration.setUseDeprecatedExecutor(false); } } ``` -------------------------------- ### Configure BlockAttackSqlParser in PaginationInterceptor Source: https://mybatis.plus/guide/block-attack-sql-parser.html Add BlockAttackSqlParser to the sqlParserList within PaginationInterceptor to enable protection against malicious SQL. You can customize the parser to exempt specific tables from these protections. ```java @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); ... List sqlParserList = new ArrayList<>(); // 攻击 SQL 阻断解析器、加入解析链 sqlParserList.add(new BlockAttackSqlParser() { @Override public void processDelete(Delete delete) { // 如果你想自定义做点什么,可以重写父类方法像这样子 if ("user".equals(delete.getTable().getName())) { // 自定义跳过某个表,其他关联表可以调用 delete.getTables() 判断 return ; } super.processDelete(delete); } }); paginationInterceptor.setSqlParserList(sqlParserList); ... return paginationInterceptor; } ``` -------------------------------- ### Custom Mapper Method for Pagination Source: https://mybatis.plus/guide/interceptor-pagination.html Define custom mapper methods to handle pagination. The return type (IPage or List) dictates how the pagination parameters are handled and how results are set. ```java IPage selectPageVo(IPage page, Integer state); // or List selectPageVo(IPage page, Integer state); ``` -------------------------------- ### TenantLineHandler Interface Definition Source: https://mybatis.plus/guide/interceptor-tenant-line.html Defines the contract for handling tenant-specific logic, including retrieving tenant IDs, specifying tenant columns, and ignoring specific tables. ```java public interface TenantLineHandler { /** * 获取租户 ID 值表达式,只支持单个 ID 值 *

* * @return 租户 ID 值表达式 */ Expression getTenantId(); /** * 获取租户字段名 *

* 默认字段名叫: tenant_id * * @return 租户字段名 */ default String getTenantIdColumn() { return "tenant_id"; } /** * 根据表名判断是否忽略拼接多租户条件 *

* 默认都要进行解析并拼接多租户条件 * * @param tableName 表名 * @return 是否忽略, true:表示忽略,false:需要解析并拼接多租户条件 */ default boolean ignoreTable(String tableName) { return false; } } ``` -------------------------------- ### Spring MVC Configuration for MybatisPlusInterceptor Source: https://mybatis.plus/guide/interceptor.html Configure MybatisPlusInterceptor with PaginationInnerInterceptor in a Spring MVC application using XML beans. ```xml ``` -------------------------------- ### MyBatis Configuration - Auto Mapping Behavior Source: https://mybatis.plus/config Defines MyBatis's automatic mapping strategy for data table fields to object properties. Options are NONE (no auto-mapping), PARTIAL (auto-mapping for non-nested results), and FULL (auto-mapping for all results). ```properties autoMappingBehavior=PARTIAL ``` -------------------------------- ### MyBatis Configuration - Cache Enabled Source: https://mybatis.plus/config Enables or disables MyBatis's second-level cache. Defaults to true. ```properties cacheEnabled=true ``` -------------------------------- ### MyBatis Configuration - Map Underscore to Camel Case Source: https://mybatis.plus/config Enables automatic mapping between database column names (snake_case) and Java property names (camelCase). This setting also affects SQL select statements generated by MyBatis-Plus. ```properties mapUnderscoreToCamelCase=true ``` -------------------------------- ### Settlement and Cache Invalidation Source: https://mybatis.plus/guide/building-the-database-layer-of-a-high-concurrency-online-gambling-platform-using-mybatis-plus Handles the settlement process, including database updates and subsequent cache invalidation for related data. Ensures that stale data is not served after settlement. ```java @Transactional public boolean settleAndInvalidate(Long orderId) { boolean ok = settlementService.doSettle(orderId); // 结算落库 if (ok) { redis.del("ORDER_DETAIL:" + orderId); redis.del("ORDER_LIST:" + getUserIdByOrder(orderId)); } return ok; } ``` -------------------------------- ### MyBatis Configuration - Aggressive Lazy Loading Source: https://mybatis.plus/config When enabled, lazy-loaded objects may have all their lazy properties loaded at once. This setting requires `lazyLoadingEnabled` to be active. ```properties aggressiveLazyLoading=true ``` -------------------------------- ### Optimistic Locking with Retries in MyBatis-Plus Source: https://mybatis.plus/guide/building-the-database-layer-of-a-high-concurrency-online-gambling-platform-using-mybatis-plus Handles concurrent updates to critical resources like wallet balances by implementing optimistic locking with a version field. Includes a retry mechanism with random backoff for failed updates due to version conflicts. ```java @Transactional public boolean debitWithRetry(Long userId, BigDecimal amount) { for (int i = 0; i < 3; i++) { Wallet w = lambdaQuery().eq(Wallet::getUserId, userId).one(); if (w == null || w.getBalance().compareTo(amount) < 0) return false; w.setBalance(w.getBalance().subtract(amount)); if (updateById(w)) return true; // version 命中即成功 try { Thread.sleep(20L * (i + 1)); } catch (InterruptedException ignored) {} } return false; } ``` -------------------------------- ### Cache Invalidation After Database Write Source: https://mybatis.plus/guide/building-the-database-layer-of-a-high-concurrency-online-gambling-platform-using-mybatis-plus Demonstrates invalidating relevant Redis caches after a successful database write operation to maintain data consistency. This is crucial for scenarios requiring strong consistency. ```java // 写库成功后删缓存(键名示例:ORDER_LIST:userId) @Transactional public void createOrderAndInvalidateCache(BetOrder req) { save(req); // DB 写入 redis.del("ORDER_LIST:" + req.getUserId()); // 失效相关缓存 } ``` -------------------------------- ### MyBatis Configuration - Local Cache Scope Source: https://mybatis.plus/config Configures the scope of MyBatis's first-level cache. SESSION (default) caches within a session, while STATEMENT disables the cache for each statement. ```properties localCacheScope=SESSION ``` -------------------------------- ### MyBatis Configuration - Default Enum Type Handler Source: https://mybatis.plus/config Specifies the default TypeHandler for enums. Options include storing enum names, ordinal values, or using custom handlers for enums implementing IEnum or marked with @EnumValue. ```properties defaultEnumTypeHandler=org.apache.ibatis.type.EnumTypeHandler ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.