目录
  • 1.在你的springboot项目下新建子模块项目
  • 2.在此模块下新建一个包与一个java类 类名: codegenerator
  • 4.配置codegenerator类

1.在你的springboot项目下新建子模块项目

pom.xml添加以下依赖:

<properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
        </dependency>
        <dependency>
            <groupid>com.baomidou</groupid>
            <artifactid>mybatis-plus-generator</artifactid>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupid>com.baomidou</groupid>
            <artifactid>mybatis-plus-extension</artifactid>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-freemarker</artifactid>
            <version>2.3.1.release</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-maven-plugin</artifactid>
            </plugin>
        </plugins>
    </build>

ps:名称随意,最好带上generator 来辨别这是代码自动生成模块

2.在此模块下新建一个包与一个java类 类名: codegenerator

完整代码如下:

import com.baomidou.mybatisplus.core.exceptions.mybatisplusexception;
import com.baomidou.mybatisplus.core.toolkit.stringpool;
import com.baomidou.mybatisplus.core.toolkit.stringutils;
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.datetype;
import com.baomidou.mybatisplus.generator.config.rules.namingstrategy;
import com.baomidou.mybatisplus.generator.engine.freemarkertemplateengine;

import java.util.arraylist;
import java.util.list;
import java.util.scanner;

/**
 * @description: 代码生成类
 */
public class codegenerator {
    //数据库连接参数
    public static string driver = "com.mysql.cj.jdbc.driver";
    public static string url = "jdbc:mysql://localhost:3306/rht_test?characterencoding=utf8&usessl=false&servertimezone=asia/shanghai&rewritebatchedstatements=true";
    public static string username="root";
    public static string password="123456";
    //父级别包名称
    public static string parentpackage = "cn.rht";
    //代码生成的目标路径
    public static string generateto = "/rht-generator/src/main/java";
    //mapper.xml的生成路径
    public static string mapperxmlpath = "/rht-generator/src/main/resources/mapper";
    //控制器的公共基类,用于抽象控制器的公共方法,null值表示没有父类
    public static string basecontrollerclassname ;
    //业务层的公共基类,用于抽象公共方法
    public static string baseserviceclassname ;
    //作者名
    public static string author = "rht.cn";
    //模块名称,用于组成包名
    public static string modelname = "portal";
    //mapper接口的模板文件,不用写后缀 .ftl
    public static string mappertempalte = "/ftl/mapper.java";

    /**
     * <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.isnotempty(ipt)) {
                return ipt;
            }
        }
        throw new mybatisplusexception("请输入正确的" + tip + "!");
    }

    /**
     * run this
     */
    public static void main(string[] args) {
        // 代码生成器
        autogenerator mpg = new autogenerator();

        // 全局配置
        globalconfig gc = new globalconfig();
        string projectpath = system.getproperty("user.dir");
        gc.setoutputdir(projectpath + generateto);
        gc.setauthor(author);
        gc.setopen(false);
        //设置时间类型为date
        gc.setdatetype(datetype.time_pack);
        //开启swagger
        //gc.setswagger2(true);
        //设置mapper.xml的resultmap
        gc.setbaseresultmap(true);
        mpg.setglobalconfig(gc);

        // 数据源配置
        datasourceconfig dsc = new datasourceconfig();
        dsc.seturl(url);
        // dsc.setschemaname("public");
        dsc.setdrivername(driver);
        dsc.setusername(username);
        dsc.setpassword(password);
        mpg.setdatasource(dsc);

        // 包配置
        packageconfig pc = new packageconfig();
        pc.setentity("model");
        //pc.setmodulename(scanner("模块名"));
        pc.setmodulename(modelname);
        pc.setparent(parentpackage);
        mpg.setpackageinfo(pc);

        // 自定义配置
        injectionconfig cfg = new injectionconfig() {
            @override
            public void initmap() {
                // to do nothing
            }
        };
        list<fileoutconfig> foclist = new arraylist<>();
        foclist.add(new fileoutconfig("/templates/mapper.xml.ftl") {
            @override
            public string outputfile(tableinfo tableinfo) {
                // 自定义输入文件名称
                return projectpath + mapperxmlpath
                        + "/" + tableinfo.getentityname() + "mapper" + stringpool.dot_xml;
            }
        });
        cfg.setfileoutconfiglist(foclist);
        mpg.setcfg(cfg);
        mpg.settemplate(new templateconfig().setxml(null));
        mpg.settemplate(new templateconfig().setmapper(mappertempalte));

        // 策略配置
        strategyconfig strategy = new strategyconfig();
        strategy.setnaming(namingstrategy.underline_to_camel);
        //字段驼峰命名
        strategy.setcolumnnaming(namingstrategy.underline_to_camel);
        //设置实体类的lombok
        strategy.setentitylombokmodel(true);
        //设置controller的父类
        if (basecontrollerclassname!=null) strategy.setsupercontrollerclass(basecontrollerclassname);
        //设置服务类的父类
        if (baseserviceclassname !=null ) strategy.setsuperserviceimplclass(baseserviceclassname);
        // strategy.
        //设置实体类属性对应表字段的注解
        strategy.setentitytablefieldannotationenable(true);
        //设置表名
        string tablename = scanner("表名, all全部表");
        if(! "all".equalsignorecase(tablename)){
            strategy.setinclude(tablename);
        }

        strategy.settableprefix(pc.getmodulename() + "_");
        strategy.setrestcontrollerstyle(true);
        mpg.setstrategy(strategy);

        // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
        mpg.settemplateengine(new freemarkertemplateengine());
        mpg.execute();
    }

}

3.在 resources 下新建 文件夹,用来存放 mapper文件

新建模板文件: mapper.java.ftl

模板完整代码如下:

package ${package.mapper};

import ${package.entity}.${entity};
import ${supermapperclasspackage};
import org.springframework.stereotype.repository;

/**
 * <p>
 * ${table.comment!} mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if kotlin>
interface ${table.mappername} : ${supermapperclass}<${entity}>
<#else>
@repository
public interface ${table.mappername} extends ${supermapperclass}<${entity}> {

}
</#if>

4.配置codegenerator类

ps:请根据自己实际路径配置

5.启动代码生成类main方法

ps:输入all 将会自动生成配置数据库下的所有配置文件,或者直接输入单表名称生成某一个表的controller,mapper,service,model层与mapper.xml文件

下面是我输入表名为:user,自动生成的部分文件信息展示

user实体类

usermapper.xml文件

如果你有很多表要生成时,但又不想全部生成时,可以在codegenerator类代码中134行代码

 //设置表名
        string tablename = scanner("表名, all全部表");
        if(! "all".equalsignorecase(tablename)){
            strategy.setinclude(tablename);
        }

替换为:

string[] tablenames = {"user","dept"};//数据库表名的集合
for (int i = 0; i <tablenames.length ; i++) {
    strategy.setinclude(tablenames);
}

来生成自己想要生成的文件

6.删除文件

最后:也是重要的一点,在您将这些文件复制到了项目模块上的时候,留下codegenerator类与文件夹下的mapper.java.ftl配置,其他生成的请及时删除

至于原因是将来业务拓展后,数据库新增表后,只要新创建表的文件,如果不删除以前生成过的文件,到时候找起来比较麻烦,没必要给自己添这层麻烦

到此这篇关于springboot项目使用mybatis-plus逆向自动生成全套代码的文章就介绍到这了,更多相关mybatis-plus逆向自动生成代码内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!