使用 MyBatis-Plus 代码生成器

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生

MyBatis-Plus 的目的是增强 MyBatis 的功能和操作,内置代码生成器可以为我们减少不少的工作量了,这里主要介绍 MyBatis-Plus 代码生成器的使用

代码生成器也是称作 MyBatis 的逆向工程,主要是用来生成 model、mapper 等层的代码,mybatis 官方也有一个 mybatis-generator 的逆向工程,功能非常强大,但生成的代码比较臃肿,生成的 Example 类用于构造复杂的筛选条件,使用起来不友好。相比起来 mybatis-plus 生成的代码简洁优雅,配合 CRUD 接口和条件构造器,使用起来也方便

代码生成器

添加依赖

代码生成器的依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>最新版本</version>
</dependency>

MyBatis-Plus 3.0.3 之后移除了自动模板引擎依赖,需要手动添加对应引擎的依赖坐标

<!-- velocity 模板引擎, 默认 -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>最新版本</version>
</dependency>

<!-- freemarker 模板引擎 -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>最新版本</version>
</dependency>

<!-- beetl 模板引擎 -->
<dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>最新版本</version>
</dependency>

生成代码

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率

public class Generator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + ":");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(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"); // 生成文件的输出目录,默认D根目录
        gc.setFileOverride(true); // 是否覆盖已有文件
        gc.setAuthor("zou");
        gc.setOpen(false); // 是否打开输出目录,默认true
        gc.setEnableCache(true); // 是否在xml中添加二级缓存配置,默认false
        gc.setSwagger2(true); // 开启 swagger2 模式,默认false

        gc.setEntityName("%sModel");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("I%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(projectPath  + "/src/main/resources/generator.properties"));
            dsc.setUrl(properties.getProperty("generator.jdbc.url"));
            // dsc.setSchemaName("public");
            dsc.setDriverName(properties.getProperty("generator.jdbc.driver"));
            dsc.setUsername(properties.getProperty("generator.jdbc.username"));
            dsc.setPassword(properties.getProperty("generator.jdbc.password"));
            mpg.setDataSource(dsc);
        } catch (IOException e) {
            throw new RuntimeException("数据源配置错误", e);
        }

        // 包名配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.shiyu");
        pc.setEntity("model");
        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) {
                // 自定义输出文件名
                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.setEntity();
        // 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); // 数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
        // strategy.setSuperEntityClass("com.shiyu.BaseEntity"); //自定义继承的Entity类全称,带包名
        // strategy.setSuperEntityColumns(new String[] {"id","gmtCreate","gmtModified"});// 自定义基础的Entity类,公共字段
        strategy.setEntityLombokModel(true); // 是否为lombok模型
        strategy.setEntityBooleanColumnRemoveIsPrefix(true); // Boolean类型字段是否移除is前缀
        strategy.setRestControllerStyle(true); // 生成 @RestController 控制器
        // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        // strategy.setInclude("upms_user"); //包含的表名
        strategy.setExclude("upms_role"); // 排除的表名

        strategy.setControllerMappingHyphenStyle(true); // 驼峰转连字符 如 umps_user 变为 upms/user
        strategy.setTablePrefix(pc.getModuleName() + "_"); // 表前缀

        mpg.setStrategy(strategy);
        // mpg.setTemplateEngine(new FreemarkerTemplateEngine()); //设置模板引擎类型,默认为 velocity
        // mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 切换为 freemarker 模板引擎
        // mpg.setTemplateEngine(new BeetlTemplateEngine()); //切换为 beetl 模板引擎
        mpg.execute();
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值