SpringBoot - Mybaits-Plus 代码生成器

SpringBoot - Mybaits-Plus 代码生成器

概述

上一篇介绍了怎么通过Entity自动更新数据库表结构,香。。。。但还不够。。。
Controller,Service,Mapper。。。怎么办,手动是不可能手动的。

Mybatis-Plus有代码生成器,可以从数据库表中自动生成上面一系列的文件。
GO 。。。 看看香不香。

组件

Mybatis-Plus 代码生成器
官网

依赖

		<!-- Mybatis-Plus 代码生成器-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.3.2</version>
		</dependency>

		<!-- Mybatis-Plus 代码生成器 模板-->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.30</version>
		</dependency>

配置

跟着官网,修改一些自己想要的参数。
默认的模板,每个模块会生成一个目录,这点不喜欢,改成集中目录。

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();
            scanner.close();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    /**
     * 自定义包路径,文件生成路径,这边配置更灵活 虽然也可以使用InjectionConfig设置FileOutConfig的方式设置路径
     * 这里直接使用Map方式注入ConfigBuilder配置对象更加直观
     * 
     * @param pc
     * @param mpg
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static void customPackagePath(PackageConfig pc, AutoGenerator mpg)
            throws NoSuchFieldException, IllegalAccessException {

        String projectPath = System.getProperty("user.dir") + "/xx";
        String mavenPath = "\\src\\main\\java\\";
        String srcPath = projectPath + mavenPath;

        String moduleName = pc.getModuleName();

        /**
         * packageInfo配置controller、service、serviceImpl、entity、mapper等文件的包路径
         * 这里包路径可以根据实际情况灵活配置
         */
        Map<String, String> packageInfo = new HashMap<>();
        packageInfo.put(ConstVal.CONTROLLER, "com.xxx.xxx.Controller");
        packageInfo.put(ConstVal.SERVICE, "com.xxx.xxx.Service");
        packageInfo.put(ConstVal.SERVICE_IMPL, "com.xxx.xxx.Service.Impl");
        packageInfo.put(ConstVal.ENTITY, "com.xxx.xxx.Entity");
        packageInfo.put(ConstVal.MAPPER, "com.xxx.xxx.Mapper");

        /**
         * pathInfo配置controller、service、serviceImpl、entity、mapper、mapper.xml等文件的生成路径
         * srcPath也可以更具实际情况灵活配置 后面部分的路径是和上面packageInfo包路径对应的源码文件夹路径
         * 这里你可以选择注释其中某些路径,可忽略生成该类型的文件,例如:注释掉下面pathInfo中Controller的路径,就不会生成Controller文件
         */
        Map<String, String> pathInfo = new HashMap<>();
        pathInfo.put(ConstVal.CONTROLLER_PATH, srcPath + "/com/xxx/xxx/Controller/");
        pathInfo.put(ConstVal.SERVICE_PATH, srcPath + "/com/xxx/xxx/Service/");
        pathInfo.put(ConstVal.SERVICE_IMPL_PATH, srcPath + "/com/xxx/xxx/Service/Impl/");
        pathInfo.put(ConstVal.ENTITY_PATH, srcPath + "/com/xxx/xxx/Entity/");
        pathInfo.put(ConstVal.MAPPER_PATH, srcPath + "/com/xxx/xxx/Mapper/");
        pathInfo.put(ConstVal.XML_PATH, projectPath + "\\src\\main\\resources\\mapper\\");
        pc.setPathInfo(pathInfo);

        /**
         * 创建configBuilder对象,传入必要的参数
         * 将以上的定义的包路径packageInfo配置到赋值到configBuilder对象的packageInfo属性上
         * 因为packageInfo是私有成员变量,也没有提交提供公共的方法,所以使用反射注入 为啥要这么干,看源码去吧
         */
        ConfigBuilder configBuilder = new ConfigBuilder(mpg.getPackageInfo(), mpg.getDataSource(), mpg.getStrategy(),
                mpg.getTemplate(), mpg.getGlobalConfig());
        Field packageInfoField = configBuilder.getClass().getDeclaredField("packageInfo");
        packageInfoField.setAccessible(true);
        packageInfoField.set(configBuilder, packageInfo);

        /**
         * 设置配置对象
         */
        mpg.setConfig(configBuilder);
    }

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

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir") + "/xx";
        String mavenPath = "\\src\\main\\java\\";
        String srcPath = projectPath + mavenPath;

        gc.setOutputDir(srcPath);
        gc.setAuthor("xx");
        gc.setOpen(false);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(
                "jdbc:mysql://localhost:3306/xxx?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("xxx");
        dsc.setPassword("xxx");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.xxx.xxx");
        mpg.setPackageInfo(pc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(com.rain.cloud.Entity.BaseEntity.class);
        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.setTemplateEngine(new VelocityTemplateEngine());

        // 自定义文件生成路径,包路径
        // 这里调用customPackagePath方法,使用可以自己在内部灵活配置路径
        // 如果不调用该方法、就会使用MyBatis-Plus默认的文件生成路径和包路径生成文件、但可以使用上面的PackageConfig做一些简单的配置
        try {
            customPackagePath(pc, mpg);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        mpg.execute();
    }
}

运行

F5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值