怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

发布时间:2021-09-05 13:35:55 作者:chen
来源:亿速云 阅读:132

本篇内容主要讲解“怎么在SpringBoot项目使用mybatis-plus逆向自动生成类”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么在SpringBoot项目使用mybatis-plus逆向自动生成类”吧!

目录

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 来辨别这是代码自动生成模块

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

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

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

完整代码如下:

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

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

模板完整代码如下:

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:请根据自己实际路径配置

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

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

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

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

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

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

User实体类

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

UserMapper.xml文件

怎么在SpringBoot项目使用mybatis-plus逆向自动生成类

如果你有很多表要生成时,但又不想全部生成时,可以在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逆向自动生成类

到此,相信大家对“怎么在SpringBoot项目使用mybatis-plus逆向自动生成类”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. Mybatis如何逆向生成使用扩展类
  2. mybatis逆向工程与分页在springboot中怎么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis springboot

上一篇:Java9中集合工厂方法的示例分析

下一篇:React的React.FC与React.Component的用法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》