### Config Command Examples Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/README.md Examples for interacting with the translation plugin's configuration settings. ```bash # 显示配置(表格格式) npm run translate -- config show ``` ```bash # 显示配置(JSON 格式) npm run translate -- config show --json ``` ```bash # 运行配置向导 npm run translate -- config init ``` ```bash # 验证配置是否正确 npm run translate -- config validate ``` ```bash # 查看可用的 AI Providers npm run translate -- config providers ``` -------------------------------- ### Translate Command Examples Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/README.md Practical examples demonstrating various translation scenarios, from basic usage to advanced options. ```bash # 翻译所有文件到所有语言(带确认提示) npm run translate ``` ```bash # 静默模式翻译到英语 npm run translate -- --lang en --quiet ``` ```bash # 翻译指定文件并跳过确认 npm run translate -- --file introduce.mdx --yes ``` ```bash # 增量翻译(仅修改过的文件) npm run translate -- --incremental ``` ```bash # 预览模式(不实际翻译) npm run translate -- --dry-run ``` ```bash # 详细模式 + 日志文件 npm run translate -- --verbose --log-file ./logs/translate.log ``` ```bash # JSON 格式输出(适合脚本集成) npm run translate -- --json > result.json ``` ```bash # 遇到错误继续执行,最多重试 3 次 npm run translate -- --continue-on-error --retry 3 ``` -------------------------------- ### Status Command Examples Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/README.md Examples for checking translation progress and status, including verbose and JSON output. ```bash # 查看各语言翻译进度 npm run translate -- status ``` ```bash # 查看详细状态(包含需要更新的文件列表) npm run translate -- status --verbose ``` ```bash # JSON 格式输出状态 npm run translate -- status --json ``` -------------------------------- ### like Example with QueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Demonstrates how to use the like method with QueryWrapper for a fuzzy name search. ```java QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.like("name", "王"); ``` -------------------------------- ### Install Dependencies Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/MIGRATION.md Run this command in your project's root directory to install new CLI dependencies for v2.0. ```bash # In the project root directory npm install ``` -------------------------------- ### Java Code Generator Example Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/code-generator.md This example demonstrates the full configuration and execution of the MyBatis-Plus AutoGenerator. It covers global configuration, data source setup, package naming, custom file output, template selection, and strategy configuration for table naming and entity generation. It requires user input for module names, table names, and database credentials. ```java import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Scanner; // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 public class CodeGenerator { /** *

* 读取控制台内容 *

*/ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("jobob"); gc.setOpen(false); // gc.setSwagger2(true); 实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("密码"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner("模块名")); pc.setParent("com.baomidou.ant"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 List focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判断自定义文件夹是否需要创建 checkDir("调用默认方法创建的目录,自定义目录用"); if (fileType == FileType.MAPPER) { // 已经生成 mapper 文件判断存在,不想重新生成返回 false return !new File(filePath).exists(); } // 允许生成模板文件 return true; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); // 写于父类中的公共字段 strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } } ``` -------------------------------- ### Complete Spring Boot Configuration Example Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/plugins/optimistic-locker.md A full Spring Boot configuration demonstrating how to integrate the OptimisticLockerInnerInterceptor with the MybatisPlusInterceptor. ```java @Configuration @MapperScan("com.yourpackage.mapper") public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; } } ``` -------------------------------- ### like Example with LambdaQueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Demonstrates how to use the like method with LambdaQueryWrapper, utilizing a method reference for the field. ```java LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.like(User::getName, "王"); ``` -------------------------------- ### Test Basic Functionality Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/MIGRATION.md Verify the installation and basic commands of the translation plugin after updating. ```bash # View help information node translation-plugin/translate.js --help # View current configuration node translation-plugin/translate.js config show # View translation status node translation-plugin/translate.js status ``` -------------------------------- ### Get Help Information Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/MIGRATION.md Access help information for the translation plugin via the command line. ```bash node translation-plugin/translate.js --help ``` -------------------------------- ### Example Update Operation and Generated SQL Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/annotation.mdx Demonstrates an example of updating a User entity and the resulting SQL generated by MyBatis-Plus when using the updateStrategy.ALWAYS configuration. ```java User user = new User(); user.setId(1L); user.setNickname("Updated Nickname"); user.setAge(30); user.setEmail("updated@example.com"); userMapper.updateById(user); ``` ```sql UPDATE sys_user SET nickname = 'Updated Nickname', age = 30, email = 'updated@example.com' WHERE id = 1; ``` -------------------------------- ### Example: Batch Update by ID with Custom Batch Size Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/ja/guides/data-interface.mdx This example demonstrates how to perform batch updates with a specified batch size. Setting a custom batch size can help manage memory and performance, especially when dealing with a large number of records. ```java // 一連の User エンティティオブジェクトがあり、バッチ更新を実行し、バッチサイズを 1 に指定していると仮定 List users = Arrays.asList( new User(1, null, "new.email1@example.com"), new User(2, null, "new.email2@example.com") ); boolean result = userService.updateBatchById(users, 1); // updateBatchById メソッドを呼び出し、バッチサイズを指定 if (result) { System.out.println("Records updated successfully."); } else { System.out.println("Failed to update records."); } ``` ```sql -- 第1バッチ UPDATE user SET email = 'new.email1@example.com' WHERE id = 1 -- 第2バッチ UPDATE user SET email = 'new.email2@example.com' WHERE id = 2 ``` -------------------------------- ### notLike Example with QueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Demonstrates how to use the notLike method with QueryWrapper to exclude fuzzy matches for a name. ```java QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.notLike("name", "王"); ``` -------------------------------- ### Insert Fill Examples Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/auto-fill-field.md Demonstrates various ways to call insert fill methods with different parameter types, including single entities, arrays, and collections. ```java // Insert fill example insertFillByCustomMethod1(H2User h2User); insertFillByCustomMethod8(H2User[] h2Users); insertFillByCustomMethod4(Collection h2User); ``` -------------------------------- ### notLike Example with LambdaQueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Demonstrates how to use the notLike method with LambdaQueryWrapper, utilizing a method reference for the field. ```java LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.notLike(User::getName, "王"); ``` -------------------------------- ### Example: Querying a User by ID Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Demonstrates how to use the `getById` method to retrieve a user record based on its primary key. Includes a check for whether the user was found. ```java // 假设要查询 ID 为 1 的用户 User user = userService.getById(1); // 调用 getById 方法 if (user != null) { System.out.println("User found: " + user); } else { System.out.println("User not found."); } ``` -------------------------------- ### Chain Update Examples Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Illustrates chain update operations for modifying database records. The lambda example shows type-safe updates using method references. ```java // 普通链式更新示例 update().set("status", "inactive").eq("name", "John").update(); // 将 name 为 "John" 的记录 status 更新为 "inactive" ``` ```java // lambda 链式更新示例 User updateUser = new User(); updateUser.setEmail("new.email@example.com"); lambdaUpdate().set(User::getEmail, updateUser.getEmail()).eq(User::getId, 1).update(); // 更新 ID 为 1 的用户的邮箱 ``` -------------------------------- ### Example: Querying a Single User (No Exception on Multiple Results) Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Shows how to use `getOne` with the `throwEx` parameter set to `false` to retrieve a single user record without throwing an exception if multiple records match the criteria. ```java // 假设有一个 QueryWrapper 对象,设置查询条件为 name = 'John Doe',并且不抛出异常 QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", "John Doe"); User user = userService.getOne(queryWrapper, false); // 调用 getOne 方法 if (user != null) { System.out.println("User found: " + user); } else { System.out.println("User not found."); } ``` -------------------------------- ### Update Fill Examples Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/auto-fill-field.md Illustrates update fill operations using collections of IDs and entity objects. Ensure correct parameter naming for successful filling. ```java // Update fill example updateFillByCustomMethod2(@Param("coll") Collection ids, @Param("et") H2User h2User); updateFillByCustomMethod4(@Param("colls") Collection ids, @Param("et") H2User h2User); ``` -------------------------------- ### Example: Retrieving User Data as a Map Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Demonstrates using `getMap` with a `QueryWrapper` to fetch a single user record and return it as a `Map`. Useful for accessing specific columns without mapping to an entity. ```java // 假设有一个 QueryWrapper 对象,设置查询条件为 name = 'John Doe',并将结果映射为 Map QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", "John Doe"); Map userMap = userService.getMap(queryWrapper); // 调用 getMap 方法 if (userMap != null) { System.out.println("User found: " + userMap); } else { System.out.println("User not found."); } ``` -------------------------------- ### Chain Query Examples Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Demonstrates how to use chain query wrappers for database record retrieval. The lambda version provides type-safe column referencing. ```java // 普通链式查询示例 query().eq("name", "John").list(); // 查询 name 为 "John" 的所有记录 ``` ```java // lambda 链式查询示例 lambdaQuery().eq(User::getAge, 30).one(); // 查询年龄为 30 的单条记录 ``` -------------------------------- ### Example: saveOrUpdateBatch Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/data-interface.mdx Demonstrates batch update or insert operations using saveOrUpdateBatch with a default batch size. Suitable for multiple entity updates/inserts. ```java // Assume a collection of User entity objects, each with an id property List users = Arrays.asList( new User(1, "Alice", "alice@example.com"), new User(2, "Bob", "bob@example.com"), new User(3, "Charlie", "charlie@example.com") ); // Perform batch update/insert using the default batch size boolean result = userService.saveOrUpdateBatch(users); // Call saveOrUpdateBatch method with default batch size if (result) { System.out.println("Users updated or saved successfully."); } else { System.out.println("Failed to update or save users."); } ``` -------------------------------- ### notBetween Example with LambdaQueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Demonstrates how to use the notBetween method with LambdaQueryWrapper, utilizing a method reference for the field. ```java LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.notBetween(User::getAge, 18, 30); ``` -------------------------------- ### Java Example: Deleting a User by Query Wrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Demonstrates how to delete a user record using the `remove` method with a `QueryWrapper` to specify the deletion criteria. Ensure the `userService` is properly initialized. ```java // 假设有一个 QueryWrapper 对象,设置删除条件为 name = 'John Doe' QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", "John Doe"); boolean result = userService.remove(queryWrapper); // 调用 remove 方法 if (result) { System.out.println("Record deleted successfully."); } else { System.out.println("Failed to delete record."); } ``` -------------------------------- ### Example: Querying a Single User by Name Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Illustrates using `getOne` with a `QueryWrapper` to fetch a single user record matching specific criteria, such as a name. Handles cases where the user might not be found. ```java // 假设有一个 QueryWrapper 对象,设置查询条件为 name = 'John Doe' QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", "John Doe"); User user = userService.getOne(queryWrapper); // 调用 getOne 方法 if (user != null) { System.out.println("User found: " + user); } else { System.out.println("User not found."); } ``` -------------------------------- ### Standard Chain-Style Update Example Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/data-interface.mdx Demonstrates a standard chain-style update to modify a record based on a specific condition. ```java update().set("status", "inactive").eq("name", "John").update(); ``` -------------------------------- ### Query with XML Configuration and Wrapper in Kotlin Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/wrapper.mdx Example of a Kotlin interface method that uses an XML configuration for custom SQL queries with a Wrapper. ```kotlin List getAll(Wrapper ew); ``` ```xml ``` -------------------------------- ### MyBatis-Plus Global Config DB Config Example Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/index.mdx Configure global database settings for MyBatis-Plus, including table prefixes and ID types. ```yaml mybatis-plus: global-config: db-config: table-prefix: tbl_ id-type: auto ``` -------------------------------- ### notBetween Example with QueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Demonstrates how to use the notBetween method with QueryWrapper to exclude a range of values for a numeric field. ```java QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.notBetween("age", 18, 30); ``` -------------------------------- ### Lambda Chain-Style Update Example Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/data-interface.mdx Illustrates a type-safe lambda chain-style update using method references for setting values and conditions. ```java User updateUser = new User(); updateUser.setEmail("new.email@example.com"); lambdaUpdate().set(User::getEmail, updateUser.getEmail()).eq(User::getId, 1).update(); ``` -------------------------------- ### Java Example: Batch Deleting Users by IDs Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Illustrates how to delete multiple user records efficiently by providing a list of their IDs to the `removeByIds` method. This is suitable for bulk deletion operations. ```java // 假设有一组 ID 列表,批量删除用户 List ids = Arrays.asList(1, 2, 3); boolean result = userService.removeByIds(ids); // 调用 removeByIds 方法 if (result) { System.out.println("Users deleted successfully."); } else { System.out.println("Failed to delete users."); } ``` -------------------------------- ### Example: saveOrUpdateBatch with specified batch size Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/data-interface.mdx Demonstrates using saveOrUpdateBatch with a custom batch size for controlling the number of operations per batch. Useful for managing large datasets. ```java // Assume a collection of User entity objects List users = Arrays.asList( new User(4, "David", "david@example.com"), new User(5, "Eve", "eve@example.com"), new User(6, "Frank", "frank@example.com") ); // Perform batch update/insert with a specified batch size of 2 boolean result = userService.saveOrUpdateBatch(users, 2); // Call saveOrUpdateBatch method with specified batch size if (result) { System.out.println("Users updated or saved successfully."); } else { System.out.println("Failed to update or save users."); } ``` -------------------------------- ### Kotlin Wrapper Usage Examples Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/wrapper.mdx Demonstrates the usage of KtQueryWrapper and KtUpdateWrapper in Kotlin for building queries and update conditions. Note that LambdaQueryWrapper and LambdaUpdateWrapper are not supported directly in Kotlin. ```kotlin val queryWrapper = KtQueryWrapper(User()).eq(User::name, "sss").eq(User::roleId, "sss2") userMapper!!.selectList(queryWrapper) val updateConditionWrapper = KtUpdateWrapper(User()).eq(User::name, "sss").eq(User::roleId, "sss2") val updateRecord = User() updateRecord.name = "newName" userMapper!!.update(updateRecord, updateConditionWrapper) val updateRecord = User() updateRecord.id = 2 updateRecord.name = "haha" userMapper.updateById(updateRecord) ``` -------------------------------- ### Query Tables with Fuzzy Matching Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/code-generator-configuration.mdx Demonstrates how to query all tables whose names start with 'sys' using the `likeTable` method. This is useful for selecting a subset of tables based on a pattern. ```java List> list = mapper.selectList( Wrappers.>query() .likeTable("sys%") ); ``` -------------------------------- ### XML Configuration for Paginated Mapper Method Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/plugins/pagination.mdx Example of an XML configuration for a mapper method that performs a paginated query, specifying the result type. ```xml ``` -------------------------------- ### notLikeLeft Example with QueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Excludes records where the 'name' field starts with '王'. Uses QueryWrapper for standard query building. ```java QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.notLikeLeft("name", "王"); ``` -------------------------------- ### Example: Update with UpdateWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/ja/guides/data-interface.mdx Use this method when you need to update records based on specific conditions defined in an UpdateWrapper. Ensure the SQL SET clause is correctly configured within the wrapper. ```java // UpdateWrapper オブジェクトがあり、更新条件を name = 'John Doe' に設定し、更新フィールドを email に設定していると仮定 UpdateWrapper updateWrapper = new UpdateWrapper<>(); updateWrapper.eq("name", "John Doe").set("email", "john.doe@newdomain.com"); boolean result = userService.update(updateWrapper); // update メソッドを呼び出し if (result) { System.out.println("Record updated successfully."); } else { System.out.println("Failed to update record."); } ``` ```sql UPDATE user SET email = 'john.doe@newdomain.com' WHERE name = 'John Doe' ``` -------------------------------- ### notLikeLeft Example with LambdaQueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Excludes records where the 'name' field starts with '王', using Lambda expressions for type safety. Uses LambdaQueryWrapper. ```java LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.notLikeLeft(User::getName, "王"); ``` -------------------------------- ### Config Command Usage Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/README.md Manage plugin configuration using commands like show, init, validate, and providers. ```bash # 显示当前配置 node translation-plugin/translate.js config show ``` ```bash # 配置初始化向导 node translation-plugin/translate.js config init ``` ```bash # 验证配置 node translation-plugin/translate.js config validate ``` ```bash # 列出所有 AI Providers node translation-plugin/translate.js config providers ``` -------------------------------- ### MyBatis-Plus Data Source Configuration Example Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/code-generator-configuration.mdx This snippet demonstrates how to configure the data source for the MyBatis-Plus code generator. It specifies the database type, connection URL, username, password, and driver class name. ```java DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MYSQL) // Set the database type, such as MySQL, Oracle, etc. .setUrl("jdbc:mysql://localhost:3306/mybatis_plus") // Database connection URL .setUsername("root") // Database username .setPassword("password") // Database password .setDriverName("com.mysql.cj.jdbc.Driver"); // Database driver class name ``` -------------------------------- ### Enable SQL Runner Initialization Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/index.mdx Configure whether to initialize the `SqlRunner` utility. Set to `true` to enable. ```yaml mybatis-plus: global-config: enable-sql-runner: true ``` -------------------------------- ### Register MybatisPlusInterceptor Bean Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/reference/index.mdx Example of registering a `MybatisPlusInterceptor` bean with an inner interceptor. ```java @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); return interceptor; } ``` -------------------------------- ### Providing Encryption Key via Command-Line Argument Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/security.md Pass the encryption key to your application at startup using command-line arguments. This is essential for decrypting configurations. ```txt --mpw.key=d1104d7c3b616f0b ``` -------------------------------- ### Configure MyBatisPlusInterceptor with Inner Interceptors Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/index.mdx Example of configuring `MybatisPlusInterceptor` with `BlockAttackInnerInterceptor` using Java Bean configuration. ```java @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); return interceptor; } ``` -------------------------------- ### Generated SQL for saveOrUpdateBatch (mixed) Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/data-interface.mdx Example SQL generated for a batch operation where some records exist and others do not. ```sql UPDATE user SET name = 'Alice', email = 'alice@example.com' WHERE id = 1 UPDATE user SET name = 'Bob', email = 'bob@example.com' WHERE id = 2 INSERT INTO user (id, name, email) VALUES (3, 'Charlie', 'charlie@example.com') ``` -------------------------------- ### Recommended Configuration for Debugging Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/MIGRATION.md Enable verbose output and log to a file for detailed debugging information. ```bash # Verbose mode + log file node translation-plugin/translate.js \ --verbose \ --log-file ./logs/translation.log ``` -------------------------------- ### Global Configuration Example Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/code-generator-configuration.mdx Demonstrates how to configure global settings for the MyBatis-Plus code generator, including output directory, author, caching, Swagger, naming patterns, and ID types. Adjust these parameters to match your project's specific needs. ```java GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setOutputDir("src/main/java") // Set output directory .setFileOverride(true) // Allow overwriting existing files .setOpen(false) // Don't automatically open output directory .setEnableCache(true) // Add secondary cache configuration in XML .setAuthor("Your Name") // Set developer name .setKotlin(false) // Don't enable Kotlin mode .setSwagger2(true) // Enable Swagger2 mode .setActiveRecord(false) // Don't enable ActiveRecord mode .setBaseResultMap(true) // Enable BaseResultMap .setBaseColumnList(true) // Enable baseColumnList .setDateType(DateType.TIME_PACK) // Set time type strategy .setEntityName("%sEntity") // Set entity naming pattern .setMapperName("%sDao") // Set Mapper naming pattern .setXmlName("%sDao") // Set Mapper XML naming pattern .setServiceName("%sService") // Set Service naming pattern .setServiceImplName("%sServiceImpl") // Set Service impl naming pattern .setControllerName("%sController") // Set Controller naming pattern .setIdType(IdType.AUTO); // Set primary key ID type to auto-increment ``` -------------------------------- ### Query All Users with list() Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Demonstrates how to retrieve all user records using the `list()` method. This is useful for fetching all entries from a table. ```java // 查询所有用户 List users = userService.list(); // 调用 list 方法 for (User user : users) { System.out.println("User: " + user); } ``` -------------------------------- ### Example: saveOrUpdate Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/data-interface.mdx Demonstrates how to use the saveOrUpdate method for a single entity. Ensure the entity has an ID annotated with @TableId. ```java // Assume a User entity object where id is the property annotated with TableId User user = new User(); user.setId(1); user.setName("John Doe"); user.setEmail("john.doe@example.com"); boolean result = userService.saveOrUpdate(user); // Call the saveOrUpdate method if (result) { System.out.println("User updated or saved successfully."); } else { System.out.println("Failed to update or save user."); } ``` -------------------------------- ### User Class with Enum Fields Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/auto-convert-enum.md Example of a User class that uses enum types for its 'age' and 'grade' properties. ```java public class User { private String name; // Name private AgeEnum age; // Age private GradeEnum grade; // Grade } ``` -------------------------------- ### application.yml Configuration for p6spy Driver Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/p6spy.mdx Configure your datasource to use the P6SpyDriver. This is a basic setup for enabling p6spy interception. ```yaml spring: datasource: driver-class-name: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:h2:mem:test # Other database configurations... ``` -------------------------------- ### Configuration Management Commands Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/MIGRATION.md Manage your translation plugin configuration using these commands. ```bash # View configuration npm run translate -- config show # Configuration wizard npm run translate -- config init # Validate configuration npm run translate -- config validate # View AI Providers npm run translate -- config providers ``` -------------------------------- ### Regenerate Configuration Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/MIGRATION.md Run the configuration wizard to generate a new config.json file. ```bash node translation-plugin/translate.js config init ``` -------------------------------- ### notLikeRight Example with QueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Excludes records where the 'name' field ends with '王'. Uses QueryWrapper for standard query building. ```java QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.notLikeRight("name", "王"); ``` -------------------------------- ### Enable Quiet Mode Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/MIGRATION.md Use the `--quiet` option to suppress the new UI elements and get a concise output. ```bash npm run translate -- --quiet ``` -------------------------------- ### SQL Example: DELETE Statement by ID Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx The SQL statement generated when deleting a record using the `removeById` method with ID 1. ```sql DELETE FROM user WHERE id = 1 ``` -------------------------------- ### Basic Code Generation with FastAutoGenerator Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/new-code-generator.mdx Demonstrates how to use FastAutoGenerator to create code with basic global, package, and strategy configurations. Ensure you have the mybatis-plus-generator dependency and a compatible template engine. ```java FastAutoGenerator.create("url", "username", "password") .globalConfig(builder -> builder .author("Baomidou") .outputDir(Paths.get(System.getProperty("user.dir")) + "/src/main/java") .commentDate("yyyy-MM-dd") ) .packageConfig(builder -> builder .parent("com.baomidou.mybatisplus") .entity("entity") .mapper("mapper") .service("service") .serviceImpl("service.impl") .xml("mapper.xml") ) .strategyConfig(builder -> builder .entityBuilder() .enableLombok() ) .templateEngine(new FreemarkerTemplateEngine()) .execute(); ``` -------------------------------- ### Get LambdaUpdateWrapper from UpdateWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Obtain a LambdaUpdateWrapper from an UpdateWrapper to use lambda expressions for type-safe update conditions. Ensure the UpdateWrapper is initialized. ```java UpdateWrapper updateWrapper = new UpdateWrapper<>(); LambdaUpdateWrapper lambdaUpdateWrapper = updateWrapper.lambda(); // Use Lambda expressions to build update conditions lambdaUpdateWrapper.set(User::getName, "李四"); ``` -------------------------------- ### Switch Data Source and Run DDL Script Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/auto-ddl.md Dynamically switch to a specific data source replica and execute a DDL script using `ShardingKey.change` and `ddlScript.run`. ```java // Switch to the MySQL replica and execute SQL script (This feature is not available in the open-source version) 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');")); ``` -------------------------------- ### Get LambdaQueryWrapper from QueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Obtain a LambdaQueryWrapper from a QueryWrapper to use lambda expressions for type-safe query conditions. Ensure the QueryWrapper is initialized. ```java QueryWrapper queryWrapper = new QueryWrapper<>(); LambdaQueryWrapper lambdaQueryWrapper = queryWrapper.lambda(); // Use Lambda expressions to build query conditions lambdaQueryWrapper.eq(User::getName, "张三"); ``` -------------------------------- ### Configuring Generation Strategies with StrategyConfig Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/reference/new-code-generator-configuration.md Define rules for code generation, including naming conventions, table/field filtering, and module-specific strategies. This example shows enabling features like capital mode, skipping views, disabling SQL filtering, and specifying table matching and prefixes. ```java StrategyConfig strategyConfig = new StrategyConfig.Builder() .enableCapitalMode() // 开启大写命名 .enableSkipView() // 开启跳过视图 .disableSqlFilter() // 禁用 SQL 过滤 .likeTable(new LikeTable("USER")) // 模糊匹配表名 .addInclude("t_simple") // 增加表匹配 .addTablePrefix("t_", "c_") // 增加过滤表前缀 .addFieldSuffix("_flag") // 增加过滤字段后缀 .build(); ``` -------------------------------- ### Database Schema Configuration Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/index.mdx Define the database schema name to be used. This is typically not required unless you are working with specific schema setups. ```yaml mybatis-plus: global-config: db-config: schema: my_schema ``` -------------------------------- ### Import SimpleQuery Utility Class Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/data-interface.mdx Import the necessary classes for using SimpleQuery. Ensure your entity's BaseMapper is injected. ```java import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.core.toolkit.support.SerializedLambda; import com.baomidou.mybatisplus.core.toolkit.support.SimpleQuery; ``` -------------------------------- ### SQL Example: DELETE Statement by Map Conditions Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx The SQL statement generated when deleting records using `removeByMap` with the condition `age = 30`. ```sql DELETE FROM user WHERE age = 30 ``` -------------------------------- ### Spring Boot Starter Configuration for p6spy Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/p6spy.mdx Configure p6spy logging format and custom appender class within a Spring Boot application. This simplifies integration. ```yaml decorator: datasource: p6spy: # Log format log-format: "\ntime:%(executionTime) || sql:%(sql)\n" # Custom logger class logging: custom custom-appender-class: com.example.testinit.config.StdoutLogger ``` -------------------------------- ### SQL Example: DELETE Statement by Name Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx The SQL statement generated when deleting a record using a `QueryWrapper` with the condition `name = 'John Doe'`. ```sql DELETE FROM user WHERE name = 'John Doe' ``` -------------------------------- ### Logging and Debugging Options Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/translation-plugin/MIGRATION.md Enable verbose or debug modes and specify a log file for detailed output. ```bash # Verbose mode npm run translate -- --verbose # Debug mode npm run translate -- --debug # Save logs to a file npm run translate -- --log-file ./logs/translation.log ``` -------------------------------- ### Query with Annotation and Wrapper in Kotlin Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/wrapper.mdx Example of a Kotlin interface method using `@Select` annotation to query with a custom SQL segment from a Wrapper. ```kotlin @Select("select * from mysql_data ${ew.customSqlSegment}") List getAll(@Param(Constants.WRAPPER) Wrapper wrapper); ``` -------------------------------- ### Execute SQL Script on Secondary MySQL Database Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/auto-ddl.md Demonstrates switching to a secondary MySQL database and executing a SQL script using `ShardingKey.change` and `ddlScript.run`. Note: This specific functionality might be limited in the open-source version. ```java // 切换到mysql从库,执行SQL脚本 (开源版本无此功能) 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');")); ``` -------------------------------- ### Column Format Configuration Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/index.mdx Configure a format string for column names, excluding primary keys. For example, adding a suffix like '_field'. ```yaml mybatis-plus: global-config: db-config: column-format: %s_field ``` -------------------------------- ### Query All Users as Maps with listMaps() Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx Shows how to retrieve all user records and map them to a list of `Map` using `listMaps()`. This is useful when you need flexible access to column data without predefined entities. ```java // 查询所有用户,并将结果映射为 Map List> userMaps = userService.listMaps(); // 调用 listMaps 方法 for (Map userMap : userMaps) { System.out.println("User Map: " + userMap); } ``` -------------------------------- ### Configure MySQL Data Source Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/reference/code-generator-configuration.mdx Sets up the data source configuration for a MySQL database, including connection URL, username, password, and driver name. Adjust these parameters to match your specific database environment. ```java DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MYSQL) // Set database type to MySQL .setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&serverTimezone=UTC") // Set database connection URL .setUsername("root") // Set database username .setPassword("password") // Set database password .setDriverName("com.mysql.cj.jdbc.Driver"); // Set database driver name ``` -------------------------------- ### notLikeRight Example with LambdaQueryWrapper Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/guides/wrapper.mdx Excludes records where the 'name' field ends with '王', using Lambda expressions for type safety. Uses LambdaQueryWrapper. ```java LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.notLikeRight(User::getName, "王"); ``` -------------------------------- ### Quick Code Generation with FastAutoGenerator Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/new-code-generator.mdx Use this snippet to directly run the code generator with predefined configurations. It allows setting author, Swagger enablement, output directory, custom data type conversions, package names, mapper XML paths, included tables, and table prefixes. It also demonstrates using the Freemarker template engine. ```java public static void main(String[] args) { FastAutoGenerator.create("url", "username", "password") .globalConfig(builder -> { builder.author("baomidou") // 设置作者 .enableSwagger() // 开启 swagger 模式 .outputDir("D://"); // 指定输出目录 }) .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> { int typeCode = metaInfo.getJdbcType().TYPE_CODE; if (typeCode == Types.SMALLINT) { // 自定义类型转换 return DbColumnType.INTEGER; } return typeRegistry.getColumnType(metaInfo); }) ) .packageConfig(builder -> builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名 .moduleName("system") // 设置父包模块名 .pathInfo(Collections.singletonMap(OutputFile.xml, "D://")) // 设置mapperXml生成路径 ) .strategyConfig(builder -> builder.addInclude("t_simple") // 设置需要生成的表名 .addTablePrefix("t_", "c_") // 设置过滤表前缀 ) .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板 .execute(); } ``` -------------------------------- ### SQL Example: DELETE Statement by Batch IDs Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/guides/data-interface.mdx The SQL statement generated when deleting multiple records using the `removeByIds` method with a list of IDs. ```sql DELETE FROM user WHERE id IN (1, 2, 3) ``` -------------------------------- ### Configure Illegal SQL Interceptor with XML Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/en/plugins/illegal-sql-intercept.md Configure the IllegalSQLInnerInterceptor in your MyBatis-Plus setup using XML. This approach is useful for non-Spring or older Spring configurations. ```xml ``` -------------------------------- ### Specify configurationFactory Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/reference/index.mdx Provide a factory class for creating Configuration instances. This factory must have a static method `getConfiguration()`. ```yaml mybatis-plus: configuration: configuration-factory: com.your.config.MyConfigurationFactory ``` -------------------------------- ### Example: Update by ID Source: https://github.com/baomidou/mybatis-plus-doc/blob/master/src/content/docs/ja/guides/data-interface.mdx Use updateById to efficiently update a single record when you know its primary key. Provide the entity object with the ID and the fields to be updated. ```java // User エンティティオブジェクトがあり、更新フィールドを email に設定し、ID に基づいて更新していると仮定 User updateEntity = new User(); updateEntity.setId(1); updateEntity.setEmail("updated.email@example.com"); boolean result = userService.updateById(updateEntity); // updateById メソッドを呼び出し if (result) { System.out.println("Record updated successfully."); } else { System.out.println("Failed to update record."); } ``` ```sql UPDATE user SET email = 'updated.email@example.com' WHERE id = 1 ```