MyBatis-Plus

repository·3.0·Indexed 12 days ago

https://github.com/baomidou/mybatis-plus

A powerful enhancement of the MyBatis framework that simplifies database development. It provides out-of-the-box CRUD operations via BaseMapper, conditional query builders like QueryWrapper, automatic pagination, and support for the Active Record pattern. It is designed to be non-intrusive, maintaining full compatibility with existing MyBatis configurations while offering features like code generation, primary key strategies, and built-in SQL injection defense.

Tokens
2.7K
Snippets
7
Records
9
Agent score
96%

What's inside MyBatis-Plus

  1. Overview of MyBatis-Plus features

    3.0

    MyBatis-Plus is an enhanced toolkit for MyBatis designed to simplify development. Key features include:

    • Full Compatibility: Works seamlessly with existing MyBatis configurations.
    • Auto Configuration: Automatic setup on application startup.
    • CRUD Interfaces: Out-of-the-box interfaces for standard database operations.
    • Query Builders: Powerful and flexible where condition wrappers (including Lambda-style).
    • Primary Key Strategies: Multiple options for generating primary keys.
    • Code Generation: Highly customizable code generator.
    • Pagination: Automatic paging operations.
    • Security: Built-in SQL injection defense.
    • Active Record: Support for the Active Record pattern.
    • Extensibility: Support for pluggable custom interfaces and built-in extensions.
  2. Key features of MyBatis-Plus

    3.0

    MyBatis-Plus is an enhancement tool for MyBatis that follows the principle of "only enhancement, no change." It simplifies CRUD operations without affecting existing MyBatis configurations.

    Core advantages include:

    • Non-intrusive: Extends MyBatis without impacting existing architecture; supports all native MyBatis features.
    • Low Overhead: Automatically injects basic CRUD operations with minimal performance loss.
    • Universal CRUD: Built-in Generic Mapper and Generic Service for single-table operations, plus a powerful Condition Builder.
    • Primary Key Strategies: Supports 4 different strategies, including a distributed unique ID generator.
    • ActiveRecord Support: Entities can inherit from the Model class to enable ActiveRecord-style CRUD.
    • Code Generation: Supports generating Mapper, Model, Service, and Controller layers via Maven plugins or code templates.
    • Built-in Plugins:
      • Pagination Plugin: Physical pagination based on MyBatis.
      • Performance Analysis Plugin: Outputs SQL statements and execution times (recommended for development/testing).
      • Global Interceptor Plugin: Provides intelligent analysis and blocking for all-table delete and update operations to prevent accidental data loss.
  3. Install MyBatis-Plus via Gradle

    3.0

    Add the corresponding implementation dependency to your build.gradle file based on your Spring Boot version.

    // SpringBoot2
    implementation group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: 'Latest Version'
    
    // SpringBoot3
    implementation group: 'com.baomidou', name: 'mybatis-plus-spring-boot3-starter', version: 'Latest Version'
    
    // SpringBoot4
    implementation group: 'com.baomidou', name: 'mybatis-plus-spring-boot4-starter', version: 'Latest Version'
  4. Install MyBatis-Plus via Maven

    3.0

    To use MyBatis-Plus, add the appropriate starter dependency to your pom.xml based on your Spring Boot version. Replace Latest Version with the current stable version (e.g., 3.5.17).

    <!-- SpringBoot2 -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>Latest Version</version>
    </dependency>
    
    <!-- SpringBoot3 -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
      <version>Latest Version</version>
    </dependency>
    
    <!-- SpringBoot4 (requires ^3.5.13) -->
    <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-spring-boot4-starter</artifactId>
    <version>Latest Version</version>
    </dependency>
  5. Install MyBatis-Plus

    3.0

    To use MyBatis-Plus, add the appropriate starter dependency to your project based on your Spring Boot version and JDK.

    Note: For versions ^3.5.9, you may need to include a specific jsqlparser dependency depending on your JDK version:

    • JDK 11+: Use mybatis-plus-jsqlparser.
    • JDK 8: Use mybatis-plus-jsqlparser-4.9.
    <!-- Maven SpringBoot2 -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>Latest Version</version>
    </dependency>
    
    <!-- Maven SpringBoot3 -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
      <version>Latest Version</version>
    </dependency>
    
    <!-- Maven SpringBoot4 -->
    <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-spring-boot4-starter</artifactId>
    <version>Latest Version</version>
    </dependency>
    
    <!-- Gradle SpringBoot2 -->
    implementation group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: 'Latest Version'
    
    <!-- Gradle SpringBoot3 -->
    implementation group: 'com.baomidou', name: 'mybatis-plus-spring-boot3-starter', version: 'Latest Version'
    
    <!-- Gradle SpringBoot4 -->
    implementation group: 'com.baomidou', name: 'mybatis-plus-spring-boot4-starter', version: 'Latest Version'
  6. Use BaseMapper and QueryWrapper for database operations

    3.0

    To enable MyBatis-Plus features for an entity, extend the BaseMapper<T> interface in your Mapper file. You can then use QueryWrapper or its Lambda-style API to perform conditional queries.

    Example: Using a Lambda-style QueryWrapper to select users where age is greater than or equal to 18 will generate the SQL: SELECT * FROM user WHERE age >= 18.

    // 1. Extend BaseMapper
    public interface UserMapper extends BaseMapper<User> {
    }
    
    // 2. Use it in your service/logic
    List<User> userList = userMapper.selectList(
            new QueryWrapper<User>()
                    .lambda()
                    .ge(User::getAge, 18)
    );
  7. Configure JSqlParser for specific JDK versions

    3.0

    For versions ^3.5.9, you may need to include an additional mybatis-plus-jsqlparser dependency depending on your JDK version to ensure compatibility.

    <!-- For JDK 11+ -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-jsqlparser</artifactId>
      <version>Latest Version</version>
    </dependency>
    
    <!-- For JDK 8 -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-jsqlparser-4.9</artifactId>
      <version>Latest Version</version>
    </dependency>
  8. Use built-in DDL error handlers: PrintlnLogErrorHandler and ThrowsErrorHandler

    3.0

    If you do not need custom logic, use the pre-defined singleton instances of the standard error handlers:

    • To log errors and continue execution: Use DdlScriptErrorHandler.PrintlnLogErrorHandler.INSTANCE.
    • To stop execution on error: Use DdlScriptErrorHandler.ThrowsErrorHandler.INSTANCE.
    // Use the logger to continue execution despite errors
    DdlScriptErrorHandler handler = DdlScriptErrorHandler.PrintlnLogErrorHandler.INSTANCE;
    
    // Use the thrower to halt execution immediately on error
    DdlScriptErrorHandler handler = DdlScriptErrorHandler.ThrowsErrorHandler.INSTANCE;
  9. Implement custom DDL script error handling with DdlScriptErrorHandler

    3.0

    When executing DDL (Data Definition Language) scripts, you can provide a custom implementation of the DdlScriptErrorHandler interface to control how errors are managed. This allows you to decide whether to log the error and continue with subsequent scripts or to throw an exception and halt the entire execution process.

    MyBatis-Plus provides two built-in implementations:

    1. PrintlnLogErrorHandler: Logs the error using MyBatis logging and allows execution to continue.
    2. ThrowsErrorHandler: Wraps the error in a SQLException and throws it, which interrupts the execution of any remaining scripts.
    // Example: Implementing a custom handler that ignores specific errors
    public class MyCustomErrorHandler implements DdlScriptErrorHandler {
        @Override
        public void handle(String sqlFile, Exception exception) throws SQLException {
            if (exception.getMessage().contains("already exists")) {
                // Log and ignore if the table/column already exists
                System.out.println("Skipping: " + sqlFile + " already exists.");
            } else {
                // Otherwise, fail the execution
                throw new SQLException("Critical DDL error in " + sqlFile, exception);
            }
        }
    }