Mybatis-Plus-Generator 初体验

Mybatis-Plus-GeneratorMybatis-Plus的插件,用于生自定义SQL。
使用很简单,下载官方的例子 mybatis-plus-samples。直接改配置就行。
主要就是修改此文件中的配置,直接运行就可以生成了。官网的用着不习惯,自己提了下变量。

添加依赖

MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.2</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>

生成代码

package com.mybatisplus.generator;

import java.util.*;

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.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

/**
 * <p>
 * mysql 代码生成器演示例子
 * </p>
 *
 * @author jobob
 * @since 2018-09-12
 */
public class MysqlGenerator {
    // 全局配置
    private final static String OUTPUT_DIR = "\\mybatisplus-generator\\src\\main\\java";// 生成文件的输出目录
    private final static String AUTHOR = "jerryjin";// 开发人员
    // 数据源配置
    private final static String DATABASE_IP = "127.0.0.1";// 数据库id
    private final static String DATABASE_NAME = "demo";// 数据库名称
    // 包配置
    private final static String PARENT = "com.mybatisplus";// 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
    private final static String MODULE_NAME = "generator";// 父包模块名
    // 自定义基类
    private final static String SuperEntity = "com.mybatisplus.generator.common.BaseEntity";// 所有实体的基类(全类名)
    private final static String SuperController = "com.mybatisplus.generator.common.BaseController";// 所有控制器的基类(全类名)

    /**
     * <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.isBlank(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 + OUTPUT_DIR);
        gc.setAuthor(AUTHOR);
        gc.setOpen(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://"+DATABASE_IP+":3306/"+DATABASE_NAME+"?useUnicode=true&useSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        // dsc.setDriverName("com.mysql.jdbc.Driver");// JDK7
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");// JDK8
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

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

        // 自定义配置
        // 注意 dto.java.ftl 模板中顶部使用的是 ${cfg.Dto}
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("Dto", pc.getParent() + ".dto");
                this.setMap(map);
            }
        };
        
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义 mapper
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + OUTPUT_DIR + "/" + PARENT.replaceAll("\\.", "/") + "/" + MODULE_NAME + "/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        // 自定义 dto
        focList.add(new FileOutConfig("/templates/dto.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + OUTPUT_DIR + "/" + PARENT.replaceAll("\\.", "/") + "/" + MODULE_NAME + "/dto/" + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
            }
        });
        
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(SuperEntity);
        strategy.setEntityLombokModel(true);//【实体】是否为lombok模型
        strategy.setSuperControllerClass(SuperController);
        strategy.setEnableSqlFilter(false); // 当enableSqlFilter为false时,Include 允许正则表达式
        // strategy.setInclude(scanner("表名"));
        strategy.setInclude(".+"); // 所有表
        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        // 使用 freemarker 引擎。默认是Velocity。反正用哪个引擎就得自己添加哪个引擎的依赖
        mpg.setTemplateEngine(new FreemarkerTemplateEngine()); 
        mpg.execute();
    }
}

代码生成器配置

以上代码中配置的含义查看 代码生成器配置

自定义模板

参考自带的模板改就行了。具代的代码就不想看了DTO的模板直接写死,试试能找到模板生成代码就行。
修改现有模板还将就,添加新模板就得自己用 InjectionConfig 注入全局属性。
也不是说这样不行,只大多数人只是想要个顺手的工具,简单好用学习成本低才是正理,毕竟我关心的是我当前要做的东西,而不是没完没了的学习一个没几天就会变的工具。还是直接 EasyCode 吧。

模板参考:
https://gitee.com/baomidou/generator/tree/develop/mybatis-plus-generator/src/main/resources/templates
或者也可以自己找到jar包看
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑虾

多情黯叹痴情癫。情癫苦笑多情难

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值