mybatis-plus生成代码

添加依赖

复制代码
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>3.3.0</version>
    </dependency>

    <!--mybatis plus 代码生成器 https://github.com/baomidou/generator-->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-generator</artifactId>
      <version>3.4.1</version>
    </dependency>
    <!-- 用于代码生成    -->
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity-engine-core</artifactId>
      <version>2.3</version>
    </dependency>

添加拦截器

复制代码
package com.uzx.compliance.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MyBatis-Plus 配置(分页、乐观锁等)。
 *
 * 主要是注册 {@link PaginationInnerInterceptor},保证 Page.total 能正确返回总条数。
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 新的分页插件,支持多种拦截器组合。
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页拦截器,使用 MySQL 方言
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInnerInterceptor.setMaxLimit(1000L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);

        // 乐观锁拦截器(如暂时不用,也可以保留不影响分页)
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

生成代码工具类

复制代码
package fi.usdx.util;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class CodeGeneratorUtil {


  public static void main(String[] args) {
    // 代码生成器
    AutoGenerator mpg = new AutoGenerator();
    //mpg.setTemplateEngine(new FreemarkerTemplateEngine());

    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    // 生成文件的输出目录
    System.out.println(System.getProperty("user.dir") + "/temp");
    gc.setOutputDir(System.getProperty("user.dir") + "/temp");
    // 指定生成的主键的ID类型
    gc.setIdType(null);
    // 开发人员
    gc.setAuthor("");
    // 是否打开输出目录
    gc.setOpen(false);
    // 是否在xml中添加二级缓存配置
    gc.setEnableCache(false);
    // 关闭 swagger2 模式
    gc.setSwagger2(false);
    // 实体命名方式
    gc.setEntityName("%sEntity");
    // mapper 命名方式
    gc.setMapperName("%sMapper");
    // Mapper xml 命名方式
    gc.setXmlName("%sMapper");
    // service 命名方式
    gc.setServiceName("%sService");
    // service impl 命名方式
    gc.setServiceImplName("%sServiceImpl");
    // controller 命名方式
    gc.setControllerName("%sController");
    gc.setBaseResultMap(true);// 生成resultMap
    gc.setBaseColumnList(true);// XML中生成基础列
    mpg.setGlobalConfig(gc);

    // 数据源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setDriverName("com.mysql.jdbc.Driver");
    dsc.setUrl(
        "jdbc:mysql://43.207.185.242:13306/usdx?useUnicode=true&characterEncoding=UTF-8&useLegacyDatetimeCode=false&useTimezone=true&serverTimezone=UTC&allowPublicKeyRetrieval=true&verifyServerCertificate=false&useSSL=false");
    dsc.setUsername("zzg");
    dsc.setPassword("baqrYDmmG6YdEj2zdPQvcTSN!");

//    dsc.setUrl(
//        "jdbc:mysql://localhost:3306/usdx?useUnicode=true&characterEncoding=UTF-8&useLegacyDatetimeCode=false&useTimezone=true"
//            + "&serverTimezone=UTC&allowPublicKeyRetrieval=true&verifyServerCertificate=false&useSSL=false");
//    dsc.setUsername("root");
//    dsc.setPassword("123456");

//    dsc.setUrl("jdbc:mysql://127.0.0.1:3306/sun?serverTimezone=UTC&useUnicode=true&useSSL=false&characterEncoding=utf8");
//    dsc.setUsername("root");
//    dsc.setPassword("cjl1234");

    // 设置数据源
    mpg.setDataSource(dsc);
    // 包配置
    PackageConfig pc = new PackageConfig();
    // 父包名
    pc.setParent("fi.usdx");
    // 模块名
//    pc.setModuleName("");
    // Entity包名
    pc.setEntity("entity");
    // Mapper包名
    pc.setMapper("mapper");
    // Controller包名
    pc.setController("controller");
    // Service包名
    pc.setService("service");
    mpg.setPackageInfo(pc);

    // 策略配置
    StrategyConfig strategy = new StrategyConfig();
    // underline_to_camel:转驼峰,no_change:无变化
    // 数据库表映射到实体的命名策略
    strategy.setNaming(NamingStrategy.underline_to_camel);
    // 数据库表字段映射到实体的命名策略
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    // 【实体】是否为lombok模型(默认 false)
    strategy.setEntityLombokModel(true);
    // 实体增加  @TableId 注解
    strategy.setEntityTableFieldAnnotationEnable(true);

    // 生成 @RestController 控制器
    strategy.setRestControllerStyle(true);
    // 实体父类
    //strategy.setSuperEntityClass(BaseEntity.class);
    // 实体父类中的字段,多个用逗号分隔
    //strategy.setSuperEntityColumns("id")
    // 表名称
    strategy.setInclude(("big_swap_monitor_record").split(","));
    // 驼峰转连字符
    strategy.setControllerMappingHyphenStyle(true);
    // 表前缀
    //strategy.setTablePrefix("t_");
    mpg.setStrategy(strategy);

    mpg.execute();
  }

}

结果展示

  1. entitiy

    Data
    @EqualsAndHashCode(callSuper = false)
    @TableName("config")
    public class ConfigEntity implements Serializable {

    复制代码
     private static final long serialVersionUID = 1L;
    
     /**
      * 自增主键
      */
     @TableId(value = "id", type = IdType.AUTO)
     private Long id;
    
     /**
      * key
      */
     @TableField("`key`")
     private String key;
    
     /**
      * value
      */
     @TableField("value")
     private String value;
    
     /**
      * 乐观锁预留
      */
     @TableField("`version`")
     private Integer version;
    
     /**
      * 逻辑删除,冗余字段
      */
     @TableField("deleted")
     private Boolean deleted;
    
     @TableField("deleted_at")
     private LocalDateTime deletedAt;
    
     @TableField(value = "updated_at",updateStrategy= FieldStrategy.NEVER)
     private LocalDateTime updatedAt;
    
     @TableField("created_at")
     private LocalDateTime createdAt;

    }

  2. mapper

    public interface ConfigMapper extends BaseMapper<ConfigEntity> {

    }

  3. service

    public interface ConfigService extends IService<ConfigEntity> {}

  4. serviceimple

    @Service
    public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, ConfigEntity> implements ConfigService {

    }

相关推荐
2501_944525543 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 预算详情页面
android·开发语言·前端·javascript·flutter·ecmascript
heartbeat..3 小时前
Redis 中的锁:核心实现、类型与最佳实践
java·数据库·redis·缓存·并发
4 小时前
java关于内部类
java·开发语言
好好沉淀4 小时前
Java 项目中的 .idea 与 target 文件夹
java·开发语言·intellij-idea
gusijin4 小时前
解决idea启动报错java: OutOfMemoryError: insufficient memory
java·ide·intellij-idea
To Be Clean Coder4 小时前
【Spring源码】createBean如何寻找构造器(二)——单参数构造器的场景
java·后端·spring
lsx2024064 小时前
FastAPI 交互式 API 文档
开发语言
吨~吨~吨~4 小时前
解决 IntelliJ IDEA 运行时“命令行过长”问题:使用 JAR
java·ide·intellij-idea
你才是臭弟弟4 小时前
SpringBoot 集成MinIo(根据上传文件.后缀自动归类)
java·spring boot·后端
短剑重铸之日4 小时前
《设计模式》第二篇:单例模式
java·单例模式·设计模式·懒汉式·恶汉式