红茶的个人站点

  • 首页
  • 专栏
  • 开发工具
  • 其它
  • 隐私政策
Awalon
Talk is cheap,show me the code.
  1. 首页
  2. 专栏
  3. Spring Boot 学习笔记
  4. 正文

从零开始 Spring Boot 7:生成框架代码

2022年5月5日 1014点热度 0人点赞 0条评论

spring boot

图源:简书 (jianshu.com)

之前在从零开始 Spring Boot 4:Mybatis Plus - 魔芋红茶's blog (icexmoon.cn)中介绍了如何在Spring Boot项目中使用Mybatis Plus。这需要手动实现很多类似于Mapper的中间类,之际上Mybatis Plus提供根据数据库自动生成相关框架代码的功能。

准备工作

首先,从Spring Initializr创建并下载一个新的Spring Boot项目。

当然也可以使用IDE工具直接生成。

为了演示自动生成代码,我设计了一个简单的购物系统可能用到的表结构,相应的SQL可以通过learn_spring_boot (github.com)获取,获取后批量执行生成表结构即可。

添加JDBC和Mybatis Plus依赖:

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

添加Mybatis Plus代码生成器依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
</dependency>

添加模板引擎依赖:

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>

Mybatis Plus的代码生成器也支持其它模板引擎或自定义模板引擎,具体可以参考代码生成器(历史版本) | MyBatis-Plus。

代码生成工具

Mybatis Plus并没有提供一个标准的开箱即用的代码生成工具,只是提供了一个基本的AutoGenerator用于生成代码,需要对相关的数据库、模板引擎、包等进行各种配置才能使用。

不过官方给出了一个代码生成工具的示例,可以见代码生成器(历史版本) | MyBatis-Plus。

根据这个示例我改写了一个简单的代码生成工具:

package cn.icexmoon.demon.shopping;
​
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
​
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
​
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
    private static final String AUThOR = "icexmoon";
    private static final String DB_URL = "jdbc:mysql://localhost:3306/shopping";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "";
    private static final String DB_DIRVER = "com.mysql.cj.jdbc.Driver";
    private static final String ROOT_PACKAGE = "cn.icexmoon.demon.shopping";
​
    /**
     * <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");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(AUThOR);
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);
​
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(DB_URL);
        // dsc.setSchemaName("public");
        dsc.setDriverName(DB_DIRVER);
        dsc.setUsername(DB_USER);
        dsc.setPassword(DB_PASSWORD);
        mpg.setDataSource(dsc);
​
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent(ROOT_PACKAGE);
        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";
​
        // 自定义输出配置
        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("调用默认方法创建的目录,自定义目录用");
                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");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
​
}

我将各种需要修改的配置整理成了类属性,按需要修改即可。

自动生成代码

一切都准备好了,现在直接运行CodeGenerator.main即可。

如果显示缺少XXXClass的错误,可以尝试通过Maven重新加载项目以更新依赖。

这个代码生成工具需要指定模块名和对应的表名以组织代码,这些都在控制台按提示输入即可:

请输入模块名:
item
请输入表名,多个英文逗号分割:
item

我这里对模块和表的划分是:

  • user

    • users

    • cart

  • order

    • order

    • order_item

  • item

    • item

运行三次代码生成工具生成相应代码即可。

第一次运行后可能会提示缺少lombok类,可以添加相关依赖解决:

     <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
     </dependency>

OK,到这里我们已经成功用Mybatis Plus自动生成了框架代码,大致长这样:

image-20220505152930724

按照模块划分,每个模块下包含:

  • controller,控制层,包含HTTP处理器。

  • entity,实体层,包含实体类。

  • mapper,映射层,包含对数据库的映射(Mapper)。

  • service,服务层,包含主要的业务逻辑。

谢谢阅读。

本篇文章的最终示例代码可以通过learn_spring_boot (github.com)获取。

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2022年8月29日

魔芋红茶

加一点PHP,加一点Go,加一点Python......

点赞
< 上一篇
下一篇 >

文章评论

取消回复

*

code

COPYRIGHT © 2021 icexmoon.cn. ALL RIGHTS RESERVED.
本网站由提供CDN加速/云存储服务

Theme Kratos Made By Seaton Jiang

宁ICP备2021001508号

宁公网安备64040202000141号