MyBatis-Plus全方位配置示例

1. MyBatis-Plus 核心配置

首先,在项目的 pom.xml 中加入MyBatis-Plus的依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.0</version> <!-- 可以根据需要选择合适版本 -->
</dependency>

2. 配置文件:application.yml

 
mybatis-plus:
  # 配置MyBatis-Plus全局配置
  global-config:
    db-config:
      # 是否开启AR模式 (Active Record)
      active-record: false
      # 主键策略
      id-type: auto
      # 是否使用插件式自动填充
      fill-strategy: false
      # 是否开启 SQL 日志
      log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

  # 配置分页插件
  configuration:
    cache-enabled: false

  # SQL性能分析插件的配置
  sql-injector: com.baomidou.mybatisplus.extension.injector.LogicSqlInjector
关键配置项说明:
  • db-config.id-type:配置主键的生成策略,auto 表示自动增长,input 表示用户手动输入主键。
  • log-impl:配置MyBatis的日志输出方式,StdOutImpl可以将SQL语句打印到控制台,便于调试。

3. MyBatis-Plus 配置类

为了方便自定义配置,通常会创建一个配置类,配置MyBatis-Plus的分页插件、性能分析插件等。

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PerformanceInterceptor;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求超出最大页后操作,true调回到首页,false 继续请求
        paginationInterceptor.setOverflow(true);
        // 设置最大单页限制数,默认500条,-1不受限制
        paginationInterceptor.setLimit(1000);
        return paginationInterceptor;
    }

    // 性能分析插件:打印SQL并且输出执行时间
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        // 设置SQL执行的最大时间,单位:ms
        performanceInterceptor.setMaxTime(1000);
        // 格式化SQL语句
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

    @Bean
    public BlockAttackInnerInterceptor blockAttackInnerInterceptor() {
        return new BlockAttackInnerInterceptor();
    }
}

4. 分页插件配置

MyBatis-Plus 提供了分页插件,来帮助开发者处理分页逻辑。在配置类中启用分页插件,并设置相关的参数。

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setOverflow(true); // 设置请求页码超出最大页后返回首页
        paginationInterceptor.setLimit(500); // 每页最大条数
        return paginationInterceptor;
    }
}

5. 全局配置:如自动填充、逻辑删除

MyBatis-Plus支持自动填充、逻辑删除等功能。

(1) 自动填充配置:

在实体类中使用注解来实现自动填充功能。如下示例:

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;

@TableName("user")
public class User {
    @TableId(type = IdType.ASSIGN_ID)//雪花算法
    private Long id;

    private String name;
    
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

    @TableLogic
    private Integer deleted; // 逻辑删除字段

    // Getters and Setters
}
(2) 全局填充策略配置:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }
}

6. 逻辑删除配置

MyBatis-Plus支持逻辑删除,你只需在实体类中使用 @TableLogic 注解标记删除字段(例如 deleted)。

  • 在 User 实体类中,添加 @TableLogic 注解来表示逻辑删除字段。
逻辑删除SQL实现:

MyBatis-Plus会自动在删除时不是真正的删除记录,而是将逻辑删除字段的值设置为“已删除”标记。

@TableLogic
private Integer deleted;

7. 代码生成器配置

MyBatis-Plus还提供了一个非常强大的代码生成器,可以自动生成实体类、Mapper接口、XML映射文件等。

 
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class CodeGenerator {

    public static void main(String[] args) {
        AutoGenerator generator = new AutoGenerator();

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java")
                    .setFileOverride(true)
                    .setActiveRecord(true)
                    .setBaseResultMap(true)
                    .setBaseColumnList(true)
                    .setAuthor("YourName");
        generator.setGlobalConfig(globalConfig);

        // 数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/yourdb?serverTimezone=UTC")
                        .setDriverName("com.mysql.cj.jdbc.Driver")
                        .setUsername("root")
                        .setPassword("password");
        generator.setDataSource(dataSourceConfig);

        // 包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.example")
                     .setMapper("mapper")
                     .setEntity("entity")
                     .setService("service")
                     .setServiceImpl("service.impl")
                     .setController("controller");
        generator.setPackageInfo(packageConfig);

        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel)
                      .setColumnNaming(NamingStrategy.underline_to_camel)
                      .setInclude("user", "order")  // 需要生成的表名
                      .setTablePrefix("t_");
        generator.setStrategy(strategyConfig);

        // 执行生成
        generator.execute();
    }
}

8. SQL性能分析插件

MyBatis-Plus提供了性能分析插件,可以打印SQL语句及执行时间,用于性能调试。

import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(1000); // 设置SQL执行的最大时间(毫秒)
        performanceInterceptor.setFormat(true); // 格式化SQL语句
        return performanceInterceptor;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值