mybatis-plus逆向工程


pom.xml文件
以下為pom文件,所需要的依賴。
除了勾選spring web默認的,逆向工程所需的依賴,其實僅僅只要3個

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- 依賴的springboot父類,統一版本號,后面依賴版本號和父類一致的可以不用寫(2.2.6)-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.dshvv</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <!-- 配置java版本(必配)和變量區 -->
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <!-- maven項目的依賴配置集(springBoot項目也屬於maven管理的項目)  -->
    <dependencies>
        <!--這是勾選springWeb后,項目初始化默認的start-->
        <!-- springboot的啟動依賴(集成tomcat): 這里是spring-boot-starter-web 而不是 spring-boot-starter  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- springboot的測試依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--這是勾選springWeb后,項目初始化默認的end-->

        <!--這是逆向工程所所需依賴,一共3個包start-->
        <!--模板引擎支持依賴包:不配置這個mybatis-plus(逆向)會報錯-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <!--java與mysql鏈接驅動:
        1.當在idea中使用springboot的快捷創建方式時,選中了mysql 和jdbc 那么pom文件中會直接有
        2.在application.yml和逆向工程時 會用到
        -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
        <!--這是逆向工程所所需依賴,一共3個包end-->
    </dependencies>

    <!-- maven項目的插件配置集(這是勾選springWeb后,項目初始化默認的)  -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

 

逆向工程類
將其復制到任意目錄,右鍵執行就行

package com.dshvv.demo;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

class CodeGenerator {
  public static void main(String[] args) {
    // 代碼生成器
    AutoGenerator mpg = new AutoGenerator();

    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    //輸出文件路徑
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("丁少華");
    gc.setOpen(false);
    gc.setFileOverride(true);
    gc.setActiveRecord(true);
    // XML 二級緩存
    gc.setEnableCache(false);
    // XML ResultMap
    gc.setBaseResultMap(true);
    // XML columList
    gc.setBaseColumnList(true);
    //生成的service接口名字首字母是否為I,這樣設置就沒有I
    gc.setServiceName("%sService");
    //實體屬性 Swagger2 注解
    gc.setSwagger2(false);
    mpg.setGlobalConfig(gc);

    // 數據源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://23.105.203.49:3306/my_blog?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("@Dsh742308560");
    mpg.setDataSource(dsc);

    // 包配置
    PackageConfig pc = new PackageConfig();
    pc.setModuleName("");
    pc.setParent("com.dshvv.demo");
    pc.setController("controller");
    pc.setService("service");
    pc.setServiceImpl("service.impl");
    pc.setMapper("dao");
    pc.setEntity("model.entity");
    mpg.setPackageInfo(pc);
    // 自定義配置
    InjectionConfig cfg = new InjectionConfig() {
      @Override
      public void initMap() {
        // to do nothing
      }
    };

    // 如果模板引擎是 freemarker
    String templatePath = "/templates/mapper.xml.ftl";
    // 自定義輸出配置
    List<FileOutConfig> focList = new ArrayList<>();
    // 自定義配置會被優先輸出
    focList.add(new FileOutConfig(templatePath) {
      @Override
      public String outputFile(TableInfo tableInfo) {
        // 自定義輸出文件名 , 如果你 Entity 設置了前后綴、此處注意 xml 的名稱會跟着發生變化!!
        return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
            + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
      }
    });
    cfg.setFileOutConfigList(focList);
    mpg.setCfg(cfg);

    // 配置模板
    TemplateConfig templateConfig = new TemplateConfig();
    templateConfig.setXml(null);
    mpg.setTemplate(templateConfig);

    // 策略配置
    StrategyConfig strategy = new StrategyConfig();
    //下划線到駝峰的命名方式
    strategy.setNaming(NamingStrategy.underline_to_camel);
    //下划線到駝峰的命名方式
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    //是否使用lombok
    strategy.setEntityLombokModel(false);
    strategy.setRestControllerStyle(true);

    //生成哪些表
    strategy.setInclude(new String[] { "user"});
    strategy.setControllerMappingHyphenStyle(true);
    strategy.setTablePrefix(pc.getModuleName() + "_");
    mpg.setStrategy(strategy);
    mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    mpg.execute();
  }
}

 

這是參考公司的源代碼,有興趣的可以看看,我只是刪除了些注釋

package com.dshvv.myblogserver.utils;



import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

class CodeGenerator {
  public static void main(String[] args) {
    // 代碼生成器
    AutoGenerator mpg = new AutoGenerator();

    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    //輸出文件路徑
    //gc.setOutputDir("D://");
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("丁少華");
    gc.setOpen(false);
    gc.setFileOverride(true);
    gc.setActiveRecord(true);
    // XML 二級緩存
    gc.setEnableCache(false);
    // XML ResultMap
    gc.setBaseResultMap(true);
    // XML columList
    gc.setBaseColumnList(true);
    //生成的service接口名字首字母是否為I,這樣設置就沒有I
    gc.setServiceName("%sService");
    //實體屬性 Swagger2 注解
    gc.setSwagger2(true);
    mpg.setGlobalConfig(gc);

    // 數據源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://23.105.203.49:3306/my_blog?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
    // dsc.setSchemaName("public");
    dsc.setDriverName("com.mysql.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("@Dsh742308560");
    mpg.setDataSource(dsc);

    // 包配置
    PackageConfig pc = new PackageConfig();
    pc.setModuleName("");
    pc.setParent("com.dshvv.myblogserver");
    pc.setController("controller");
    pc.setService("service");
    pc.setServiceImpl("service.impl");
    pc.setMapper("dao");
    pc.setEntity("model.entity");
    mpg.setPackageInfo(pc);


    //或者
    //pc.setModuleName("");
    //pc.setParent("");
    //pc.setController("com.example.demo.web");
    //pc.setService("com.example.demo.service");
    //pc.setServiceImpl("com.example.demo.service.impl");
    //pc.setMapper("com.example.demo.mapper");
    //pc.setEntity("com.example.demo.model");
// 自定義配置
    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";

    // 自定義輸出配置
    List<FileOutConfig> focList = new ArrayList<>();
    // 自定義配置會被優先輸出
    focList.add(new FileOutConfig(templatePath) {
      @Override
      public String outputFile(TableInfo tableInfo) {
        // 自定義輸出文件名 , 如果你 Entity 設置了前后綴、此處注意 xml 的名稱會跟着發生變化!!
        return projectPath + "/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("調用默認方法創建的目錄");
                return false;
            }
        });*/
    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);
    //是否使用lombok
    strategy.setEntityLombokModel(true);
    strategy.setRestControllerStyle(true);
    // 自定義實體父類
    // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
    // 自定義實體,公共字段
    // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
    // 自定義 mapper 父類
    // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
    // 自定義 service 父類
    // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
    // 自定義 service 實現類父類
    // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
    // 自定義 controller 父類
    // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
    // 【實體】是否生成字段常量(默認 false)
    // public static final String ID = "test_id";
    // strategy.setEntityColumnConstant(true);
    // 【實體】是否為構建者模型(默認 false)
    // public User setName(String name) {this.name = name; return this;}
    // strategy.setEntityBuilderModel(true);

    //生成哪些表
    strategy.setInclude(new String[] { "user"});
    strategy.setControllerMappingHyphenStyle(true);
    strategy.setTablePrefix(pc.getModuleName() + "_");
    mpg.setStrategy(strategy);
    mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    mpg.execute();
  }

}
View Code

 

然后右鍵運行該類

 

 

其他
如果開啟了Swagger和Lombok,則需要添加如下依賴,不然生成后,運行會報錯

<!--lombok用來簡化實體類-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<!--swagger用來生成api文檔-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM