MyBatis-Puls代码生成器 SpringBoot下使用MyBatis-Puls代码生成器的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

MyBatis-Puls代码生成器 SpringBoot下使用MyBatis-Puls代码生成器的方法

GuessHat   2021-03-15 我要评论
想了解SpringBoot下使用MyBatis-Puls代码生成器的方法的相关内容吗,GuessHat在本文为您仔细讲解MyBatis-Puls代码生成器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:MyBatis-Puls代码生成器,SpringBoot,MyBatis-Puls代码生成器,下面大家一起来学习吧。

1.官方地址:

http://mybatis.plus/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B

2.数据库结构:

在这里插入图片描述

3.依赖导入

 <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
      <version>5.1.39</version>
    </dependency>
        <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-generator</artifactId>
      <version>3.4.0</version>
    </dependency>

    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.30</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>

配置freemarker是因为myBatis中默认的引擎是freemarker,支持自定义引擎

3.目录结构

在这里插入图片描述

4.官方生成器类

CodeGenerator

public class CodeGenerator {
  /**
   * <p>
   * 读取控制台内容
   * </p>
   */
  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");
    /**
     * 这里需要设定一下保存的地址是本项目下的/src/main/java
     */
    gc.setOutputDir(projectPath + "/maven1018/src/main/java");
    gc.setAuthor("XYD");
    gc.setOpen(false);
    // gc.setSwagger2(true); 实体属性 Swagger2 注解
    mpg.setGlobalConfig(gc);

    // 数据源配置
    /**
     * 设置数据库名称和数据库账户密码
     */
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://localhost:3306/temporary?useUnicode=true&useSSL=false&characterEncoding=utf8");
    // dsc.setSchemaName("public");
    dsc.setDriverName("com.mysql.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("12345");
    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";

    /**
     * 这里定义的是生成xml文档的输出配置,存放在resource下
     */
    // 自定义输出配置
//    List<FileOutConfig> focList = new ArrayList<>();
    // 自定义配置会被优先输出
//    focList.add(new FileOutConfig(templatePath) {
//      @Override
//      public String outputFile(TableInfo tableInfo) {
//        // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
//        return projectPath + "/maven1018/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"); //注释这行否则生成的实体类中没有Id变量

    strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
    strategy.setControllerMappingHyphenStyle(true);
    strategy.setTablePrefix(pc.getModuleName() + "_");
    mpg.setStrategy(strategy);
    mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    mpg.execute();
  }

}

5. 代码生成后的配置

  • 默认生成的代码中实体类是没有id属性的,在代码生成类中注释掉strategy.setSuperEntityColumns("id");
  • 默认生成的mapper对象上是没有@Mapper注解,需要在主配置类中加入@MapperScan注解,进行mapper扫描
@SpringBootApplication
@MapperScan("com.example.crount.mapper")
public class Demo1018Application {

  public static void main(String[] args) {
    SpringApplication.run(Demo1018Application.class, args);
  }

}

另外自己要运行代码进行数据库访问,所以application.properties中也要配置数据源

# 数据库配置
spring.datasource.url=jdbc:mysql:///temporary?characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=12345

#连接池配置
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

6.controller开发

注入service,修改访问的地址,写入访问的方法

@RestController
public class StudentController {

  @Autowired
  private IStudentService studentService;

  @GetMapping("/demo1")
  public String m1(){
    Student student = studentService.getById(3);
    return student.getSSex();
  }

}

7.生成的代码放到主配置类的同级目录下,运行代码

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们