1、添加依赖

1>添加 代码生成器 依赖

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

2>添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。

Velocity(默认):

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.1</version>
</dependency>

Freemarker:

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

Beetl:

<dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>3.0.13.RELEASE</version>
</dependency>

2、话不多说,直接上代码

  1 package com.example.shiro.generator;
  2 
  3 import com.baomidou.mybatisplus.annotation.DbType;
  4 import com.baomidou.mybatisplus.generator.AutoGenerator;
  5 import com.baomidou.mybatisplus.generator.config.*;
  6 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  7 import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  8 import org.junit.Test;
  9 
 10 /**
 11  *  运行此方法生成mybatis代码
 12  *  生成代码自动放入对应目录
 13  * @author wangshu
 14  * @create 2019/10/18
 15  */
 16 public class MyBatisGeneratorRun {
 17     //数据库类型
 18     private final DbType dbType = DbType.MYSQL;
 19     //数据库连结信息
 20     private final String dbUrl = "jdbc:mysql://***:3306/***?useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai&useSSL=false&autoReconnect=true&autoReconnectForPools=true&allowMultiQueries=true";
 21     private final String driver = "com.mysql.cj.jdbc.Driver";
 22     private final String userName = "***";
 23     private final String password = "***";
 24 
 25     //项目名
 26     private final String projectName = "***";
 27     //指定包名
 28     private final String packageName = "***";
 29     //controller基础类
 30     private final String superControllerClass = packageName + ".common.BaseController";
 31     //entity基础类
 32     private final String superEntityClass = packageName + ".common.BaseEntity";
 33     //模块名 如果有模块名,则需在模块名前加. 例:.log
 34     private final String moduleName = "";
 35     //作者名
 36     private final String author = "wangshu";
 37     //指定生成的表名
 38     private final String[] tableNames = new String[]{"log", "demo"};
 39 
 40 
 41     @Test
 42     public void generateCode() {
 43         //serviceNameStartWithI:user -> UserService, 设置成true: user -> IUserService
 44         generateByTables(false, packageName, tableNames);
 45     }
 46     /**
 47      * 根据表自动生成
 48      * @param serviceNameStartWithI 默认为false
 49      * @param packageName      包名
 50      * @param tableNames      表名
 51      * @author Terry
 52      */
 53     private void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
 54         //配置数据源
 55         DataSourceConfig dataSourceConfig = getDataSourceConfig();
 56         // 策略配置
 57         StrategyConfig strategyConfig = getStrategyConfig(tableNames);
 58         //全局变量配置
 59         GlobalConfig globalConfig = getGlobalConfig(serviceNameStartWithI);
 60         //包名配置
 61         PackageConfig packageConfig = getPackageConfig(packageName);
 62         //自动生成
 63         atuoGenerator(dataSourceConfig, strategyConfig, globalConfig, packageConfig);
 64     }
 65     /**
 66      * 集成
 67      * @param dataSourceConfig 配置数据源
 68      * @param strategyConfig  策略配置
 69      * @param config      全局变量配置
 70      * @param packageConfig  包名配置
 71      * @author Terry
 72      */
 73     private void atuoGenerator(DataSourceConfig dataSourceConfig, StrategyConfig strategyConfig, GlobalConfig config, PackageConfig packageConfig) {
 74         new AutoGenerator()
 75                 .setGlobalConfig(config)
 76                 .setDataSource(dataSourceConfig)
 77                 .setStrategy(strategyConfig)
 78                 .setPackageInfo(packageConfig)
 79                 .setTemplateEngine(new FreemarkerTemplateEngine())
 80                 .execute();
 81     }
 82     /**
 83      * 设置包名
 84      * @param packageName 父路径包名
 85      * @param packageName 模块名
 86      * @return PackageConfig 包名配置
 87      * @author Terry
 88      */
 89     private PackageConfig getPackageConfig(String packageName) {
 90         return new PackageConfig()
 91                 .setParent(packageName)
 92                 .setXml("mapper.xml" + moduleName)
 93                 .setMapper("mapper." + moduleName)
 94                 .setController("controller." + moduleName)
 95                 .setEntity("entity." + moduleName);
 96     }
 97     /**
 98      * 全局配置
 99      * @param serviceNameStartWithI false
100      * @return GlobalConfig
101      * @author Terry
102      */
103     private GlobalConfig getGlobalConfig(boolean serviceNameStartWithI) {
104         GlobalConfig globalConfig = new GlobalConfig();
105         globalConfig
106                 .setBaseColumnList(true)
107                 .setBaseResultMap(true)
108                 .setActiveRecord(false)
109                 //作者
110                 .setAuthor(author)
111                 //设置输出路径
112                 .setOutputDir(getOutputDir(projectName))
113                 .setFileOverride(true);
114         if (!serviceNameStartWithI) {
115             //设置service名
116             globalConfig.setServiceName("%sService");
117         }
118         return globalConfig;
119     }
120     /**
121      * 返回项目路径
122      * @param projectName 项目名
123      * @return 项目路径
124      * @author Terry
125      */
126     private String getOutputDir(String projectName) {
127 //        String path = this.getClass().getClassLoader().getResource("").getPath();
128 //        int index = path.indexOf(projectName);
129         return "D:/IntelliJ IDEA 2019.2/workSpace/" + projectName + "/src/main/java/";
130     }
131     /**
132      * 策略配置
133      * @param tableNames 表名
134      * @return StrategyConfig
135      * @author Terry
136      */
137     private StrategyConfig getStrategyConfig(String... tableNames) {
138         return new StrategyConfig()
139                 // 全局大写命名 ORACLE 注意
140                 .setCapitalMode(true)
141                 //从数据库表到文件的命名策略
142                 .setNaming(NamingStrategy.underline_to_camel)
143                 //需要生成的的表名,多个表名传数组
144                 .setInclude(tableNames)
145                 //公共父类
146                 .setSuperControllerClass(superControllerClass)
147                 .setSuperEntityClass(superEntityClass)
148                 // 写于父类中的公共字段
149                 .setSuperEntityColumns("id")
150                 //使用lombok
151                 .setEntityLombokModel(true)
152                 //rest风格
153                 .setRestControllerStyle(true);
154     }
155     /**
156      * 配置数据源
157      * @return 数据源配置 DataSourceConfig
158      * @author Terry
159      */
160     private DataSourceConfig getDataSourceConfig() {
161         return new DataSourceConfig().setDbType(dbType)
162                 .setUrl(dbUrl)
163                 .setUsername(userName)
164                 .setPassword(password)
165                 .setDriverName(driver);
166     }
167     /**
168      * 根据表自动生成
169      * @param packageName 包名
170      * @param tableNames 表名
171      * @author Terry
172      */
173     @SuppressWarnings("unused")
174     private void generateByTables(String packageName, String... tableNames) {
175         generateByTables(true, packageName, tableNames);
176     }
177 }

如果有更好的方式,欢迎交流

也可参考官网教程,实现一份适合自己的代码生成器 https://mp.baomidou.com/guide/generator.html

posted on 2019-10-21 10:39  望~舒  阅读(10231)  评论(0编辑  收藏  举报