### Batch Operations Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/IService.md Example methods demonstrating batch operations for creating, updating, deleting, and syncing users. ```APIDOC ## Batch Operations Example ### Description This section provides examples of how to use batch operations within a service implementation. ### bulkCreateUsers Creates users in batch. ```java public boolean bulkCreateUsers(List users) ``` ### bulkUpdateUsers Updates users in batch. ```java public boolean bulkUpdateUsers(List users) ``` ### deactivateUsers Deactivates users by their IDs in batch. ```java public boolean deactivateUsers(List userIds) ``` ### deleteUsers Deletes users in batch with rollback on error. ```java public boolean deleteUsers(List userIds) ``` ### syncUsers Synchronizes users by inserting or updating them in batch. ```java public boolean syncUsers(List externalUsers) ``` ``` -------------------------------- ### UserService saveBatch Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/IService.md Example of using saveBatch to perform bulk user creation with a specified batch size. ```java @Service public class UserService extends ServiceImpl { public void bulkCreateUsers(List users) { userService.saveBatch(users, 500); } } ``` -------------------------------- ### updateBatchById Usage Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/IService.md Example demonstrating how to update a batch of users by their primary keys with a specified batch size. ```java List users = userService.list(); users.forEach(u -> u.setStatus(2)); userService.updateBatchById(users, 500); ``` -------------------------------- ### Complete Service Implementation Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/IService.md Demonstrates a full implementation of IService, showcasing batch operations, custom queries, and pagination. ```java @Service @Slf4j public class UserService extends ServiceImpl implements IService { @Autowired private UserMapper userMapper; /** * Create users in batch */ public boolean bulkCreateUsers(List users) { return saveBatch(users, 500); } /** * Update users in batch */ public boolean bulkUpdateUsers(List users) { return updateBatchById(users, 500); } /** * Deactivate users by IDs */ public boolean deactivateUsers(List userIds) { // Create update entities List updates = userIds.stream() .map(id -> { User u = new User(); u.setId(id); u.setStatus(0); return u; }) .collect(Collectors.toList()); return updateBatchById(updates); } /** * Delete users with rollback on error */ public boolean deleteUsers(List userIds) { return removeBatchByIds(userIds); } /** * Sync users (insert or update) */ public boolean syncUsers(List externalUsers) { return saveOrUpdateBatch(externalUsers); } /** * Query with pagination */ public IPage getActiveUsers(int pageNum, int pageSize) { return page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper() .eq(User::getStatus, 1) .orderByDesc(User::getCreateTime) ); } /** * Custom complex query */ public List searchUsers(UserSearchDto searchDto) { return list( new LambdaQueryWrapper() .like(StringUtils.isNotBlank(searchDto.getName()), User::getName, searchDto.getName()) .eq(searchDto.getStatus() != null, User::getStatus, searchDto.getStatus()) .between(searchDto.getMinAge() != null && searchDto.getMaxAge() != null, User::getAge, searchDto.getMinAge(), searchDto.getMaxAge()) .orderByDesc(User::getCreateTime) ); } } ``` -------------------------------- ### Complete Entity Example with MyBatis-Plus Annotations Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Annotations.md Provides a comprehensive example of an entity class annotated for MyBatis-Plus, showcasing various configurations like primary keys, column mapping, auto-fill, logical deletion, optimistic locking, transient fields, and custom type handlers. ```java @TableName("sys_user") @KeySequence("seq_user_id") // Oracle/PostgreSQL public class User { // Primary key with distributed ID strategy @TableId(value = "user_id", type = IdType.ASSIGN_ID) private Long id; // Basic field with column name mapping @TableField("user_name") private String name; // Field with auto-fill strategy @TableField(fill = FieldFill.INSERT) @OrderBy(isDesc = true, sort = 1) private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; // Logical delete field @TableLogic(value = "0", delval = "1") private Integer deleted; // Optimistic lock version @Version private Integer version; // Transient field (not persisted) @TableField(exist = false) private String tempData; // Custom type handler @TableField(typeHandler = "com.example.JsonTypeHandler") private String attributes; // Getter/Setter methods... } ``` -------------------------------- ### saveOrUpdateBatch Usage Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/IService.md Example demonstrating the usage of saveOrUpdateBatch to process a collection of users. ```java userService.saveOrUpdateBatch(users); ``` -------------------------------- ### Querying with Pagination and Custom Logic Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/IService.md Examples of performing paginated queries and custom complex queries. ```APIDOC ## Querying with Pagination and Custom Logic ### Description Demonstrates how to implement paginated queries and custom search logic using the service methods. ### getActiveUsers Queries active users with pagination and ordering. ```java public IPage getActiveUsers(int pageNum, int pageSize) ``` ### searchUsers Performs a custom complex query based on search criteria. ```java public List searchUsers(UserSearchDto searchDto) ``` ``` -------------------------------- ### Complete Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/QueryWrapper.md Demonstrates various ways to use QueryWrapper for building complex SQL queries, including multi-condition queries, nested conditions, and map-based conditions. ```APIDOC ## Complete Example ### Multi-condition query ```java // Multi-condition query List users = userMapper.selectList( new QueryWrapper() .select("id", "name", "email", "age") .eq("status", 1) .ge("age", 18) .like("name", "ali") .isNotNull("email") .orderByDesc("create_time") .last("LIMIT 10") ); ``` ### With nested conditions ```java // With nested conditions List users = userMapper.selectList( new QueryWrapper() .eq("status", 1) .and(w -> w.eq("type", "admin").or().eq("type", "moderator")) .between("age", 18, 65) ); ``` ### With map-based conditions ```java // With map-based conditions Map conditions = new HashMap<>(); conditions.put("status", 1); conditions.put("department_id", 5); List users = userMapper.selectList( new QueryWrapper().allEq(conditions) ); ``` ``` -------------------------------- ### Service Layer Examples with Wrappers Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Wrappers.md Illustrates the use of Wrappers within a service layer for common operations like finding active users, deactivating users, and searching with dynamic criteria. ```java @Service public class UserService { @Autowired private UserMapper userMapper; public List findActiveUsers() { return userMapper.selectList( Wrappers.lambdaQuery() .eq(User::getStatus, 1) .orderByDesc(User::getCreateTime) ); } public void deactivateUsers(List ids) { userMapper.update(null, Wrappers.lambdaUpdate() .set(User::getStatus, 0) .in(User::getId, ids) ); } public IPage searchUsers(UserSearchDto search, int pageNum, int pageSize) { return userMapper.selectPage( new Page<>(pageNum, pageSize), Wrappers.lambdaQuery() .like(StringUtils.isNotBlank(search.getName()), User::getName, search.getName()) .eq(search.getStatus() != null, User::getStatus, search.getStatus()) .between(search.getMinAge() != null && search.getMaxAge() != null, User::getAge, search.getMinAge(), search.getMaxAge()) .orderByDesc(User::getCreateTime) ); } } ``` -------------------------------- ### Optimistic Locking Usage Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Annotations.md Provides a practical example demonstrating how optimistic locking with the @Version annotation prevents concurrent modification issues by failing updates when the version number mismatches. ```java // Thread 1: Load user with version=1 User user1 = userMapper.selectById(1L); // Thread 2: Load same user with version=1 User user2 = userMapper.selectById(1L); // Thread 1: Update - succeeds, version becomes 2 user1.setName("Alice"); userMapper.updateById(user1); // UPDATE succeeds // Thread 2: Update - fails (version check fails) user2.setName("Bob"); userMapper.updateById(user2); // UPDATE 0 rows (version mismatch) ``` -------------------------------- ### Configure Pagination Plugin with Java Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/configuration.md Recommended approach for configuring the pagination plugin using a `MybatisPlusInterceptor` bean. This example sets a max page size, enables join optimization, and specifies the database type. ```java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // Pagination interceptor PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(); paginationInterceptor.setMaxLimit(500L); // Max page size paginationInterceptor.setOptimizeJoin(true); paginationInterceptor.setDbType(DbType.MYSQL); interceptor.addInnerInterceptor(paginationInterceptor); // Optimistic locking interceptor (optional) OptimisticLockerInnerInterceptor optimisticLocker = new OptimisticLockerInnerInterceptor(); interceptor.addInnerInterceptor(optimisticLocker); // Dynamic table name interceptor (optional) DynamicTableNameInnerInterceptor dynamicTableName = new DynamicTableNameInnerInterceptor(); dynamicTableName.setTableNameHandler((sql, tableName) -> { // Custom table name logic return tableName; }); interceptor.addInnerInterceptor(dynamicTableName); return interceptor; } } ``` -------------------------------- ### Complete MyBatis-Plus Configuration Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/configuration.md A comprehensive Java configuration class for MyBatis-Plus, including pagination, optimistic locking, dynamic table names, meta object handling, and SQL injection. ```java @Configuration @MapperScan("com.example.mapper") public class MybatisPlusConfiguration { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // Pagination PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL); paginationInterceptor.setMaxLimit(500L); paginationInterceptor.setOptimizeJoin(true); interceptor.addInnerInterceptor(paginationInterceptor); // Optimistic locking interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // Dynamic table names DynamicTableNameInnerInterceptor dynamicTableName = new DynamicTableNameInnerInterceptor(); dynamicTableName.setTableNameHandler((sql, tableName) -> tableName + "_" + TableShardingUtil.getShardSuffix() ); interceptor.addInnerInterceptor(dynamicTableName); return interceptor; } @Bean public MetaObjectHandler metaObjectHandler() { return new MyMetaObjectHandler(); } @Bean public ISqlInjector sqlInjector() { return new DefaultSqlInjector(); } } ``` -------------------------------- ### removeBatchByIds Usage Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/IService.md Example showing how to remove multiple users by their IDs using removeBatchByIds. ```java userService.removeBatchByIds(Arrays.asList(1L, 2L, 3L)); ``` -------------------------------- ### Pagination with Condition Building Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Shows how to build complex query conditions dynamically for pagination. This example uses a `QueryWrapper` to add various filters based on user query parameters. ```APIDOC ## Pagination with Condition Building ### Description Builds dynamic query conditions for pagination based on provided criteria. ### Code Example ```java public Page queryUsers(int pageNum, int pageSize, UserQuery query) { Page page = new Page<>(pageNum, pageSize); QueryWrapper wrapper = new QueryWrapper<>(); if (StringUtils.isNotBlank(query.getName())) { wrapper.like("name", query.getName()); } if (query.getMinAge() != null) { wrapper.ge("age", query.getMinAge()); } if (query.getMaxAge() != null) { wrapper.le("age", query.getMaxAge()); } if (query.getDepartmentId() != null) { wrapper.eq("department_id", query.getDepartmentId()); } wrapper.orderByDesc("create_time"); return userMapper.selectPage(page, wrapper); } ``` ``` -------------------------------- ### LambdaQueryWrapper orderByAsc Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Use orderByAsc to sort results in ascending order. Multiple columns can be specified for sequential sorting. ```java wrapper.orderByAsc(User::getCreateTime); wrapper.orderByAsc(User::getDepartmentId, User::getAge); ``` -------------------------------- ### Group By with Having Clause Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Shows how to perform grouping on query results and apply a HAVING clause to filter grouped data. This example selects specific columns and aggregates data. ```java // Group by with having Page> page = new Page<>(1, 10); List> results = userMapper.selectMaps(page, new LambdaQueryWrapper() .select("department_id, COUNT(*) as count, AVG(age) as avg_age") .groupBy(User::getDepartmentId) .having("COUNT(*) > ?", 5) ); ``` -------------------------------- ### Implement Dynamic Table Name Handling Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/configuration.md Configure a MybatisPlusInterceptor to dynamically set table names, for example, by adding a timestamp suffix. ```java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // Dynamic table name DynamicTableNameInnerInterceptor dynamicTableName = new DynamicTableNameInnerInterceptor(); dynamicTableName.setTableNameHandler((sql, tableName) -> { // Example: add timestamp suffix String year = String.valueOf(LocalDate.now().getYear()); return tableName + "_" + year; }); interceptor.addInnerInterceptor(dynamicTableName); return interceptor; } } ``` -------------------------------- ### LambdaQueryWrapper groupBy Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Use groupBy to add a GROUP BY clause to your SQL query. You can specify one or more columns for grouping. ```java wrapper.groupBy(User::getDepartmentId, User::getStatus); ``` -------------------------------- ### Get and Set Records for a Page Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Retrieves or sets the list of entities for the current page. Returns an empty list if no records are found. ```java List getRecords(); Page setRecords(List records); ``` ```java Page page = new Page<>(1, 10); userMapper.selectPage(page, null); List users = page.getRecords(); ``` -------------------------------- ### Use MyBatis-Plus Query Wrapper Source: https://github.com/baomidou/mybatis-plus/blob/3.0/README.md Example of using MyBatis-Plus's QueryWrapper with lambda syntax to perform a conditional select operation. ```java List userList = userMapper.selectList( new QueryWrapper() .lambda() .ge(User::getAge, 18) ); ``` -------------------------------- ### Safe SQL Query Practices Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/errors.md Provides examples of secure coding practices to prevent SQL injection. It emphasizes using method parameters for values and lambda wrappers for type-safe queries, avoiding the use of user input for column names. ```java // Safe - always use method parameters wrapper.eq("column_name", userInput); // Parameter binding // NOT: wrapper.eq(userInput, value); // Never use user input as column name ``` ```java // Safe - use lambda wrappers new LambdaQueryWrapper() .eq(User::getName, userInput); // Type-safe, SQL injection proof ``` -------------------------------- ### Create a MyBatis-Plus Mapper Interface Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/README.md An example of a MyBatis-Plus mapper interface that extends BaseMapper, automatically providing CRUD operations without requiring XML configuration. ```java @Mapper public interface UserMapper extends BaseMapper { // CRUD operations auto-generated // No XML required } ``` -------------------------------- ### Get and Set Total Records for a Page Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Retrieves or sets the total number of records that match the query. This is crucial for calculating the total number of pages. ```java long getTotal(); Page setTotal(long total); ``` ```java page.setTotal(150); long total = page.getTotal(); ``` -------------------------------- ### Get By ID and Get One Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/IService.md Retrieve single records using either their ID or a query wrapper. The getOne method allows for an option to throw an exception if multiple records are found. ```java T getById(Serializable id); T getOne(Wrapper queryWrapper, boolean throwEx); ``` -------------------------------- ### Add SQL at Query Beginning Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md The first method allows you to prepend custom SQL to the beginning of the query. This is less common but can be used for specific SQL constructs. ```java wrapper.first("SELECT SQL_CALC_FOUND_ROWS"); ``` -------------------------------- ### apply Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/QueryWrapper.md Applies a raw SQL fragment with parameter binding. ```APIDOC ## apply ### Description Applies raw SQL fragment with parameter binding. ### Method ```java QueryWrapper apply(String applySql, Object... params); ``` ### Example ```java wrapper.apply("DATE(create_time) = ?", "2025-01-01"); wrapper.apply("YEAR(create_time) > ?", 2024); ``` ``` -------------------------------- ### Sort Configuration Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Methods for getting and setting sort order information. ```APIDOC ## getOrders / setOrders ### Description Gets or sets sort order information for the page. ### Method Signatures ```java List orders(); Page setOrders(List orders); ``` ### Example ```java List orders = new ArrayList<>(); orders.add(OrderItem.desc("create_time")); orders.add(OrderItem.asc("name")); page.setOrders(orders); ``` ``` -------------------------------- ### first Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Adds a SQL fragment at the beginning of the query. ```APIDOC ## first Adds SQL at the beginning. ### Signature ```java LambdaQueryWrapper first(String sqlFirst); ``` ``` -------------------------------- ### getCurrent / setCurrent Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Gets or sets the current page number. This is a 1-based index. ```APIDOC ## getCurrent / setCurrent ### Description Gets or sets the current page number (1-based). ### Method Signature ```java long getCurrent(); Page setCurrent(long current); ``` ### Example ```java page.setCurrent(2); long pageNum = page.getCurrent(); ``` ``` -------------------------------- ### Generated SQL for Query Wrapper Source: https://github.com/baomidou/mybatis-plus/blob/3.0/README.md The SQL statement generated by MyBatis-Plus for the preceding QueryWrapper example. ```sql SELECT * FROM user WHERE age >= 18 ``` -------------------------------- ### Get SELECT Clause String Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/QueryWrapper.md The `getSqlSelect` method returns the string representation of the SELECT clause. ```java String getSqlSelect(); ``` -------------------------------- ### Page() Constructor Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a new Page instance with default values for current page (1) and page size (10). ```APIDOC ## Page() ### Description Creates a page with default size of 10 and current page of 1. ### Method `public Page()` ``` -------------------------------- ### Page Constructor with All Parameters Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a page with all parameters specified: current page, records per page, total records, and the search count flag. This is the most comprehensive constructor. ```java public Page(long current, long size, long total, boolean searchCount); ``` ```java Page page = new Page<>(1, 10, 50, true); ``` -------------------------------- ### getSize / setSize Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Gets or sets the page size, which defines the number of records to display per page. ```APIDOC ## getSize / setSize ### Description Gets or sets the page size (records per page). ### Method Signature ```java long getSize(); Page setSize(long size); ``` ### Example ```java page.setSize(20); long pageSize = page.getSize(); ``` ``` -------------------------------- ### LambdaQueryWrapper having Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Use having to add a HAVING clause after a GROUP BY clause. This allows filtering groups based on aggregate conditions. ```java wrapper.groupBy(User::getDepartmentId) .having("COUNT(*) > ?", 10); ``` -------------------------------- ### Configure PaginationInnerInterceptor Options Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/configuration.md Set up the PaginationInnerInterceptor to customize pagination behavior. Key options include specifying the database type, setting a maximum page size limit, and enabling SQL optimization for COUNT and JOIN queries. ```java PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(); // Database type (required) paginationInterceptor.setDbType(DbType.MYSQL); // Supported types: MYSQL, MARIADB, ORACLE, DB2, H2, HSQL, SQLITE, // POSTGRESQL, SQLSERVER, PHOENIX, GAUSSDB, CLICKHOUSE, INFORMIX // Maximum page size limit (default: no limit) paginationInterceptor.setMaxLimit(500L); // Optimize COUNT SQL (default: true) paginationInterceptor.setOptimizeCountSql(true); // Optimize JOIN in COUNT (default: false) paginationInterceptor.setOptimizeJoin(true); // Override COUNT SQL statement ID // paginationInterceptor.setCountSqlInjector(countSqlInjector); ``` -------------------------------- ### getRecords / setRecords Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Gets or sets the list of entities for the current page. Returns an empty list if no records are found. ```APIDOC ## getRecords / setRecords ### Description Gets or sets the list of entities for this page. ### Method Signature ```java List getRecords(); Page setRecords(List records); ``` ### Returns - `getRecords()`: List of entities (empty list if none) ### Example ```java Page page = new Page<>(1, 10); userMapper.selectPage(page, null); List users = page.getRecords(); ``` ``` -------------------------------- ### Implement a Service Layer with MyBatis-Plus Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/README.md Demonstrates a service class extending ServiceImpl, providing custom methods for querying active users, searching users with pagination, and batch creating users. ```java @Service public class UserService extends ServiceImpl { public List findActiveUsers() { return list( Wrappers.lambdaQuery() .eq(User::getStatus, 1) .orderByDesc(User::getCreateTime) ); } public IPage searchUsers(String name, int pageNum, int pageSize) { return page( new Page<>(pageNum, pageSize), Wrappers.lambdaQuery() .like(StringUtils.isNotBlank(name), User::getName, name) .orderByDesc(User::getCreateTime) ); } public boolean batchCreateUsers(List users) { return saveBatch(users, 500); } } ``` -------------------------------- ### LambdaQueryWrapper orderByDesc Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Use orderByDesc to sort results in descending order. Multiple columns can be specified for sequential sorting. ```java wrapper.orderByDesc(User::getCreateTime); wrapper.orderByDesc(User::getUpdateTime, User::getId); ``` -------------------------------- ### Builder/Fluent Methods Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Demonstrates method chaining for configuring Page objects. ```APIDOC ## Builder/Fluent Methods ### Description All setter methods return the Page object for method chaining, allowing for a fluent API style. ### Example ```java Page page = new Page(1, 10) .setTotal(150) .setOptimizeJoinOfCountSql(true) .setMaxLimit(100L); ``` ``` -------------------------------- ### Multi-condition Query with QueryWrapper Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/QueryWrapper.md Demonstrates building a query with multiple conditions including select fields, equality, range, pattern matching, null checks, ordering, and limiting results. ```java // Multi-condition query List users = userMapper.selectList( new QueryWrapper() .select("id", "name", "email", "age") .eq("status", 1) .ge("age", 18) .like("name", "ali") .isNotNull("email") .orderByDesc("create_time") .last("LIMIT 10") ); ``` -------------------------------- ### Query Building with QueryWrapper Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/types.md Demonstrates building queries using MyBatis-Plus's QueryWrapper, supporting both string-based and lambda-based syntax for flexible query construction. ```java // String-based new QueryWrapper() .eq("status", 1) .like("name", "ali"); ``` ```java // Lambda-based new LambdaQueryWrapper() .eq(User::getStatus, 1) .like(User::getName, "ali"); ``` ```java // Factory method Wrappers.lambdaQuery() .eq(User::getStatus, 1); ``` -------------------------------- ### getTotal / setTotal Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Gets or sets the total number of records matching the query. This is crucial for calculating the total number of pages. ```APIDOC ## getTotal / setTotal ### Description Gets or sets the total number of records matching the query. ### Method Signature ```java long getTotal(); Page setTotal(long total); ``` ### Example ```java page.setTotal(150); long total = page.getTotal(); ``` ``` -------------------------------- ### Basic Pagination Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Demonstrates how to perform basic pagination using MyBatis-Plus. It shows how to initialize a Page object and use it with a mapper method to retrieve paginated results. ```APIDOC ## Basic Pagination ### Description Performs basic pagination by retrieving a specified range of records. ### Code Example ```java Page page = new Page<>(1, 10); userMapper.selectPage(page, new QueryWrapper().eq("status", 1)); System.out.println("Total records: " + page.getTotal()); System.out.println("Total pages: " + page.getPages()); System.out.println("Records: " + page.getRecords()); ``` ``` -------------------------------- ### Get SQL SET Clause Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaUpdateWrapper.md Retrieves the generated SET clause string from the LambdaUpdateWrapper. Useful for inspecting the generated SQL. ```java String getSqlSet(); ``` -------------------------------- ### LambdaQueryWrapper orderBy Conditional Example Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Use orderBy with a condition and a boolean flag to specify ascending or descending order for one or more columns. ```java boolean sortDescending = true; wrapper.orderBy(true, !sortDescending, User::getCreateTime); ``` -------------------------------- ### Conditional Query Building Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Illustrates how to dynamically build a query wrapper based on variable conditions. This approach allows for flexible query construction. ```java // Conditional building LambdaQueryWrapper wrapper = new LambdaQueryWrapper() .eq(User::getStatus, 1); if (minAge != null) { wrapper.ge(User::getAge, minAge); } if (maxAge != null) { wrapper.le(User::getAge, maxAge); } if (StringUtils.isNotBlank(searchName)) { wrapper.like(User::getName, searchName); } List users = userMapper.selectList(wrapper); ``` -------------------------------- ### Pagination with IPage Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/types.md Illustrates how to implement pagination in MyBatis-Plus by creating an IPage object and passing it along with a query wrapper to the selectPage method. ```java IPage page = new Page<>(1, 10); userMapper.selectPage(page, queryWrapper); ``` -------------------------------- ### Basic Query with Wrappers Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Wrappers.md Constructs a basic SQL query using the query() wrapper to filter users by status. ```java List users = userMapper.selectList( Wrappers.query() .eq("status", 1) ); ``` -------------------------------- ### Add SQL at the Beginning Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/UpdateWrapper.md The `first` method adds a custom SQL string at the very beginning of the generated SQL statement. ```java UpdateWrapper first(String sqlFirst); ``` -------------------------------- ### Get Generated SET Clause Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/UpdateWrapper.md Retrieve the generated SET clause string from the UpdateWrapper. Useful for debugging or custom SQL construction. ```java String setSql = wrapper.getSqlSet(); // Result: "status = ?, update_time = ?" ``` -------------------------------- ### Get and Set Page Size Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Retrieves or sets the number of records to display per page. This value affects pagination calculations. ```java long getSize(); Page setSize(long size); ``` ```java page.setSize(20); long pageSize = page.getSize(); ``` -------------------------------- ### Default Page Constructor Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a page with default settings: current page 1 and a page size of 10. Use when no specific pagination parameters are needed initially. ```java public Page(); ``` -------------------------------- ### Page(long current, long size, long total) Constructor Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a new Page instance with specified current page, page size, and the total number of records. ```APIDOC ## Page(long current, long size, long total) ### Description Creates a page with specified current, size, and total records. ### Method `public Page(long current, long size, long total)` ### Example ```java Page page = new Page<>(2, 10, 150); // Page 2, 10 records per page, 150 total records ``` ``` -------------------------------- ### Get Parameter Name-Value Pairs Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/UpdateWrapper.md Obtain a map of all parameter names and their corresponding values set in the UpdateWrapper. This can be helpful for inspecting the parameters before execution. ```java Map params = wrapper.getParamNameValuePairs(); ``` -------------------------------- ### Page Constructor with Current, Size, and Total Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a page with specified current page, records per page, and the total number of records. Use when the total count is known upfront. ```java public Page(long current, long size, long total); ``` ```java Page page = new Page<>(2, 10, 150); ``` -------------------------------- ### Get Entity Class Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md The getEntityClass method returns the Class object of the entity being queried. This is helpful when you need to work with the entity type programmatically. ```java Class entityClass = wrapper.getEntityClass(); ``` -------------------------------- ### Get Wrapped Entity Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md The getEntity method returns the entity object that the LambdaQueryWrapper is currently wrapping. This can be useful for inspecting the entity's state. ```java T entity = wrapper.getEntity(); ``` -------------------------------- ### Advanced Configuration Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Methods for advanced pagination and query optimization settings. ```APIDOC ## setOptimizeJoinOfCountSql ### Description Sets whether to optimize COUNT queries when JOINs are used. ### Method Signature ```java Page setOptimizeJoinOfCountSql(boolean optimizeJoinOfCountSql); ``` --- ## setMaxLimit ### Description Sets the maximum page size limit. This overrides the global pagination plugin limit. ### Method Signature ```java Page setMaxLimit(Long maxLimit); ``` ### Example ```java // Prevent requesting pages larger than 500 page.setMaxLimit(500L); ``` --- ## setCountId ### Description Sets a custom SQL statement ID for the COUNT query. ### Method Signature ```java Page setCountId(String countId); ``` ``` -------------------------------- ### Add MyBatis-Plus Spring Boot 3 Starter Dependency (Java 17+) Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/configuration.md Use this dependency for Spring Boot 3 and Java 17+ projects to integrate MyBatis-Plus. ```xml com.baomidou mybatis-plus-spring-boot3-starter 3.5.x ``` -------------------------------- ### Get and Set Current Page Number Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Retrieves or sets the current page number, which is 1-based. This is used to determine which set of records to fetch. ```java long getCurrent(); Page setCurrent(long current); ``` ```java page.setCurrent(2); long pageNum = page.getCurrent(); ``` -------------------------------- ### Page(long current, long size, long total, boolean searchCount) Constructor Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a new Page instance with all parameters specified: current page, page size, total records, and a flag to control the total count query. ```APIDOC ## Page(long current, long size, long total, boolean searchCount) ### Description Creates a page with all parameters specified. ### Method `public Page(long current, long size, long total, boolean searchCount)` ### Example ```java Page page = new Page<>(1, 10, 50, true); ``` ``` -------------------------------- ### Get Parameter Name-Value Pairs Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaUpdateWrapper.md Retrieves all parameter name-value pairs used in the update wrapper. Useful for debugging or custom SQL generation. ```java Map getParamNameValuePairs(); ``` -------------------------------- ### Clear Query Conditions Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Call the clear method to reset all conditions and column selections in the LambdaQueryWrapper, effectively starting a new query build. ```java wrapper.clear(); ``` -------------------------------- ### Page Constructor with Current and Size Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a page with a specified current page number and records per page. The total number of records defaults to 0. Use when you know the desired page and size but not the total count yet. ```java public Page(long current, long size); ``` ```java Page page = new Page<>(1, 10); ``` -------------------------------- ### Page(long current, long size, boolean searchCount) Constructor Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a new Page instance with specified current page, page size, and a flag to control whether to query the total count of records. ```APIDOC ## Page(long current, long size, boolean searchCount) ### Description Creates a page with searchCount flag (whether to query total count). ### Method `public Page(long current, long size, boolean searchCount)` ### Parameters #### Path Parameters - **current** (long) - Required - Current page number - **size** (long) - Required - Records per page - **searchCount** (boolean) - Required - true=query total, false=skip count query ### Example ```java // Skip count query for first page preview Page page = new Page<>(1, 10, false); ``` ``` -------------------------------- ### LambdaQueryWrapper Constructors Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Demonstrates the creation of LambdaQueryWrapper instances. Use the default constructor for an empty wrapper, pass an entity to extract conditions, or provide an entity class to bind the wrapper. ```java public LambdaQueryWrapper(); ``` ```java public LambdaQueryWrapper(T entity); ``` ```java public LambdaQueryWrapper(Class entityClass); ``` -------------------------------- ### Constructors Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Provides constructors for initializing LambdaQueryWrapper instances. ```APIDOC ## LambdaQueryWrapper() ### Description Creates an empty wrapper without an entity. ### Method Signature `public LambdaQueryWrapper()` ``` ```APIDOC ## LambdaQueryWrapper(T entity) ### Description Creates a wrapper with entity for auto-extracting conditions. ### Method Signature `public LambdaQueryWrapper(T entity)` ``` ```APIDOC ## LambdaQueryWrapper(Class entityClass) ### Description Creates a wrapper bound to a specific entity class. ### Method Signature `public LambdaQueryWrapper(Class entityClass)` ``` -------------------------------- ### apply Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaQueryWrapper.md Applies a raw SQL fragment with parameter binding to the query. This allows for complex conditions that cannot be expressed through standard methods. ```APIDOC ## apply Applies raw SQL fragment with parameter binding. ### Signature ```java LambdaQueryWrapper apply(String applySql, Object... params); LambdaQueryWrapper apply(boolean condition, String applySql, Object... params); ``` ### Example ```java wrapper.apply("DATE(create_time) = ?", "2025-01-01"); wrapper.apply("ABS(age - ?) < 5", 30); ``` ``` -------------------------------- ### LambdaUpdateWrapper Deactivate Inactive Users Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/LambdaUpdateWrapper.md Deactivates users who have not logged in for a specified period by updating their status and setting a deactivation timestamp. This example demonstrates using time-based conditions. ```java int result = userMapper.update( new LambdaUpdateWrapper() .set(User::getStatus, 0) .set(User::getDeactivatedTime, System.currentTimeMillis()) .lt(User::getLastLoginTime, System.currentTimeMillis() - 90*24*3600*1000) ); ``` -------------------------------- ### Page Constructor with Search Count Flag Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a page with specified current page and records per page, and a boolean flag to control whether to query the total count. Set `searchCount` to `false` to skip the count query, which can improve performance for large datasets or when the total count is not needed. ```java public Page(long current, long size, boolean searchCount); ``` ```java // Skip count query for first page preview Page page = new Page<>(1, 10, false); ``` -------------------------------- ### Enable/Disable COUNT Query Execution Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Determines whether to execute a COUNT query to get the total number of records. Set to false in the constructor to skip the count query. ```java default boolean searchCount(); ``` -------------------------------- ### Apply Raw SQL Fragment with Parameter Binding Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/QueryWrapper.md The `apply` method enables the use of raw SQL fragments with parameter binding, ensuring safer query construction. ```java QueryWrapper apply(String applySql, Object... params); ``` ```java wrapper.apply("DATE(create_time) = ?", "2025-01-01"); ``` ```java wrapper.apply("YEAR(create_time) > ?", 2024); ``` -------------------------------- ### Page(long current, long size) Constructor Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Creates a new Page instance with specified current page number and page size. The total number of records defaults to 0. ```APIDOC ## Page(long current, long size) ### Description Creates a page with specified current page and size. Total defaults to 0. ### Method `public Page(long current, long size)` ### Parameters #### Path Parameters - **current** (long) - Required - Current page number (1-based) - **size** (long) - Required - Records per page ### Request Example ```java Page page = new Page<>(1, 10); ``` ``` -------------------------------- ### Add MyBatis-Plus Spring Boot Starter Dependency (Java 8+) Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/configuration.md Include this dependency in your project for Spring Boot 2 and Java 8+ environments to enable MyBatis-Plus auto-configuration. ```xml com.baomidou mybatis-plus-boot-starter 3.5.x ``` -------------------------------- ### Configure Page with Builder Pattern Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Page.md Initialize and configure a Page object using chained setter methods. This allows for setting total records, optimizing join queries, and defining maximum limits. ```java Page page = new Page(1, 10) .setTotal(150) .setOptimizeJoinOfCountSql(true) .setMaxLimit(100L); ``` -------------------------------- ### Usage of @TableName Annotation Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Annotations.md Demonstrates how to use the @TableName annotation to map a Java class to a specific database table. Examples show basic usage, specifying a schema, and enabling auto-generation of resultMap. ```java @TableName("sys_user") public class User { // Fields } ``` ```java // With schema @TableName(value = "user", schema = "public") public class User { // PostgreSQL schema } ``` ```java // Auto-generate resultMap for complex type mapping @TableName(value = "user", autoResultMap = true) public class User { // Nested objects or complex types } ``` -------------------------------- ### Wrapper Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/types.md Abstract base for all query/update wrappers. Manages SQL generation and parameter binding. ```APIDOC ## Wrapper ### Description Abstract base for all query/update wrappers. Manages SQL generation and parameter binding. ### Package `com.baomidou.mybatisplus.core.conditions` ### Fields - `entity` (T): The entity object. - `entityClass` (Class): The entity class. - `expression` (MergeSegments): The SQL expression segments. - `paramNameSeq` (AtomicInteger): Sequence for parameter names. - `paramNameValuePairs` (Map): Map of parameter names to values. ### Methods - `abstract String getSqlSegment()`: Get the SQL segment for this wrapper. - `Map getParamNameValuePairs()`: Get the map of parameter names to values. - `T getEntity()`: Get the entity object. - `Class getEntityClass()`: Get the entity class. ### Used by BaseMapper methods accepting Wrapper parameter ``` -------------------------------- ### Usage of @TableId Annotation with Different Strategies Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/Annotations.md Illustrates the use of the @TableId annotation to define primary keys with different generation strategies. Examples cover database auto-increment, MyBatis-Plus distributed IDs, UUIDs, and manual input. ```java @TableName("sys_user") public class User { // Auto-increment by database @TableId(type = IdType.AUTO) private Long id; } ``` ```java // MyBatis-Plus generated distributed ID @TableId(value = "user_id", type = IdType.ASSIGN_ID) private Long userId; ``` ```java // UUID string @TableId(type = IdType.ASSIGN_UUID) private String id; ``` ```java // Manual input @TableId(type = IdType.INPUT) private Long id; ``` -------------------------------- ### Select Maps with Wrapper Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/api-reference/BaseMapper.md Fetches records as maps, allowing selection of specific columns. Supports pagination and streaming results. ```java List> selectMaps(@Param(Constants.WRAPPER) Wrapper queryWrapper); ``` ```java void selectMaps(@Param(Constants.WRAPPER) Wrapper queryWrapper, ResultHandler> resultHandler); ``` ```java List> selectMaps(IPage> page, @Param(Constants.WRAPPER) Wrapper queryWrapper); ``` ```java void selectMaps(IPage> page, @Param(Constants.WRAPPER) Wrapper queryWrapper, ResultHandler> resultHandler); ``` ```java List> results = userMapper.selectMaps( new QueryWrapper() .select("name", "age", "email") .ge("age", 18) ); ``` ```java // Retrieve specific columns as maps for (Map map : results) { String name = (String) map.get("name"); Integer age = (Integer) map.get("age"); } ``` -------------------------------- ### Field Fill Handler Setup for Automatic Field Population Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/errors.md Ensure the MetaObjectHandler is registered as a Spring component and that fields intended for auto-filling have the correct annotations and setters. Without a registered handler, fields like 'createTime' will remain null after insertion. ```java @TableName("sys_user") public class User { @TableField(fill = FieldFill.INSERT) private Long createTime; // Must have setter } // Missing MetaObjectHandler bean @Component // Must be registered public class MyMetaObjectHandler extends MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "createTime", Long.class, System.currentTimeMillis()); } } // Without handler, fill doesn't occur User user = new User(); user.setName("Alice"); userMapper.insert(user); // createTime will be null (not filled) ``` -------------------------------- ### MyBatis-Plus Maven Dependencies Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/README.md Include these dependencies in your pom.xml file. Choose the appropriate starter based on your Spring Boot version. ```xml com.baomidou mybatis-plus-boot-starter 3.5.x com.baomidou mybatis-plus-spring-boot3-starter 3.5.x ``` -------------------------------- ### Wrappers Factory Utility Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/types.md Provides static factory methods for conveniently creating QueryWrapper, LambdaQueryWrapper, UpdateWrapper, and LambdaUpdateWrapper instances. ```java public class Wrappers { public static QueryWrapper query(); public static QueryWrapper query(T entity); public static LambdaQueryWrapper lambdaQuery(); public static LambdaQueryWrapper lambdaQuery(T entity); public static UpdateWrapper update(); public static UpdateWrapper update(T entity); public static LambdaUpdateWrapper lambdaUpdate(); public static LambdaUpdateWrapper lambdaUpdate(T entity); } ``` ```java Wrappers.query().eq("status", 1) Wrappers.lambdaQuery(user).eq(User::getAge, 18) ``` -------------------------------- ### Wrappers Utility Class Source: https://github.com/baomidou/mybatis-plus/blob/3.0/_autodocs/types.md A factory class providing static methods to create various types of wrapper instances (QueryWrapper, LambdaQueryWrapper, etc.) for building SQL queries. ```APIDOC ## Wrappers Utility Class ### Description Factory for generating query and update wrappers, simplifying the creation of dynamic SQL conditions. ### Methods - **query()**: Creates a new `QueryWrapper`. - **query(T entity)**: Creates a `QueryWrapper` initialized with the given entity. - **lambdaQuery()**: Creates a new `LambdaQueryWrapper`. - **lambdaQuery(T entity)**: Creates a `LambdaQueryWrapper` initialized with the given entity. - **update()**: Creates a new `UpdateWrapper`. - **update(T entity)**: Creates an `UpdateWrapper` initialized with the given entity. - **lambdaUpdate()**: Creates a new `LambdaUpdateWrapper`. - **lambdaUpdate(T entity)**: Creates a `LambdaUpdateWrapper` initialized with the given entity. ### Example ```java // Using QueryWrapper Wrappers.query().eq("status", 1); // Using LambdaQueryWrapper Wrappers.lambdaQuery(user).eq(User::getAge, 18); ``` ### Package `com.baomidou.mybatisplus.core.toolkit` ```