情景:有时搭好项目框架后,需要编写业务代码时,比较繁琐,苞米豆搞了个mybaits-plus-generator,可以生产业务的基础模板,舒服的不行啊,以下贴一下代码生成的相关代码。使用
适用版本:JDK1.8 和 Mysql数据库
先看一下生成代码项目目录,如下:
项目下common文件夹下生成代码要用到的方法,稍后会把项目下载路径发出来,这里展示一下关键的代码:
1、首先在pom.xm中添加maven相关依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
</parent>
<groupId>com.seeker</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<name>project</name>
<properties>
<java.version>1.8</java.version>
<mybatis-plus.version>3.1.1</mybatis-plus.version>
<druid.version>1.1.9</druid.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<commons-io.version>2.4</commons-io.version>
<fastjson.version>1.2.69</fastjson.version>
<shiro.version>1.5.3</shiro.version>
<jwt.version>3.3.0</jwt.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Mybatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- Fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- Shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!-- Freemaker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、生成代码类:此类会生成前后端代码,前端生成vue,后端生成java代码。
package com.seeker.project.generator.tool;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 代码生成器演示
* </p>
*/
public class MpGenerator {
public static void main(String[] args) {
MpGenerator generator = new MpGenerator();
String[] includeTables = new String[]{"sys_user"};
String moduleName = "sys";
String driverName = "com.mysql.jdbc.Driver";
String username = "root";
String password = "1234";
String packageName = "com.seeker.project";
String url="jdbc:mysql://192.168.1.20:3306/plat_shop?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true";
generator.generator(driverName, username, password, url, moduleName, includeTables, packageName);
}
public static void generator(String driverName, String username, String password, String url, String moduleName, String[] includeTables, String packageName) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
//String packageName = "com.zhuoyue.modules";
String projectPath = "D:\\demo\\gen"; // Global.getProjectPath();
String resourceDir = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
String javaDir = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator;
String basePath = javaDir + packageName.replace(".", File.separator) + File.separator + moduleName;
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(javaDir);
gc.setFileOverride(true);
gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
// .setKotlin(true) 是否生成 kotlin 代码
gc.setAuthor("seeker_lqq");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
gc.setServiceName("%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName(driverName);
dsc.setUsername(username);
dsc.setPassword(password);
dsc.setUrl(url);
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
// strategy.setTablePrefix(new String[]{"gen", "sys", "in"});// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(includeTables); // 需要生成的表
// strategy.setExclude(new String[]{"tool"}); // 排除生成的表
// 自定义实体,公共字段
strategy.setSuperEntityColumns(new String[]{"remarks", "del_flag", "create_by", "create_date", "create_time", "update_by", "update_date", "update_time", "create_office_id"});
// lombok
strategy.setEntityLombokModel(true);
// rest
strategy.setRestControllerStyle(true);
// 自定义 controller 父类
strategy.setSuperControllerClass("com.seeker.project.common.base.BaseController");
// 自定义实体父类
strategy.setSuperEntityClass("com.seeker.project.common.base.DataEntity");
// 自定义 service 父类
strategy.setSuperServiceClass("com.seeker.project.common.base.CrudService");
// 自定义 service 实现类父类
strategy.setSuperServiceImplClass("com.seeker.project.common.base.CrudService");
// 自定义 mapper 父类
strategy.setSuperMapperClass("com.seeker.project.common.base.CrudDao");
// 【实体】是否生成字段常量(默认 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【实体】是否为构建者模型(默认 false)
// public User setName(String name) {this.name = name; return this;}
// strategy.setEntityBuilderModel(true);
// strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(packageName);
pc.setMapper("dao");
pc.setController("web");
pc.setModuleName(moduleName);
mpg.setPackageInfo(pc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("test", this.getConfig().getGlobalConfig().getAuthor() + " tool");
// SQL
map.put("menu_id", "" + IdWorker.getId());
map.put("menu_id_list", "" + IdWorker.getId());
map.put("menu_id_insert", "" + IdWorker.getId());
map.put("menu_id_update", "" + IdWorker.getId());
map.put("menu_id_delete", "" + IdWorker.getId());
map.put("hasTimestamp", false);
map.put("hasTimestamp", false);
map.put("hasBigDecimal", false);
map.put("hasQuery", true);
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// 调整 xml 生成目录演示
String mapperPath = resourceDir + File.separator + "mapper";
focList.add(initXmlFileOutConfig("/tmpl/generator/admin_mybatis/mapper.xml.ftl", mapperPath));
// 前台页面
String apiPath = projectPath + File.separator + "api";
String viewPath = projectPath + File.separator + "views" + File.separator;
focList.add(initApiFileOutConfig("/tmpl/generator/front_mybatis/api.ftl", apiPath, ".js"));
focList.add(initVueViewFileOutConfig("/tmpl/generator/front_mybatis/index.ftl", viewPath, "index", false));
focList.add(initVueViewFileOutConfig("/tmpl/generator/front_mybatis/edit.ftl", viewPath, "edit", true));
focList.add(initVueViewFileOutConfig("/tmpl/generator/front_mybatis/eForm.ftl", viewPath, "form", true));
focList.add(initVueViewFileOutConfig("/tmpl/generator/front_mybatis/header.ftl", viewPath, "header", true));
// 调整 mapper 生成目录演示
focList.add(initFileOutConfig("/tmpl/generator/admin_mybatis/mapper.java.ftl", basePath + File.separator + "dao", "Dao.java"));
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 关闭默认 xml 生成,调整生成 至 根目录
TemplateConfig tc = new TemplateConfig();
tc.setController("/tmpl/generator/admin_mybatis/controller.java");
tc.setEntity("/tmpl/generator/admin_mybatis/entity.java");
tc.setService("/tmpl/generator/admin_mybatis/service.java");
tc.setMapper("");
// tc.setXml("/tmpl/generator/ftl/mapper.xml");
tc.setXml("");
tc.setServiceImpl("");
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
// 打印注入设置【可无】
// System.err.println(mpg.getCfg().getMap().get("abc"));
}
public static FileOutConfig initVueViewFileOutConfig(String templatePath, String basePath, String outFile, boolean ismodule) {
FileOutConfig fileOutConfig = new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
String extmodule = ismodule ? "module" + File.separator : "";
return basePath + File.separator + getTablePath(tableInfo) + extmodule + outFile + ".vue";
}
};
return fileOutConfig;
}
public static FileOutConfig initViewFileOutConfig(String templatePath, String basePath, String outFile) {
FileOutConfig fileOutConfig = new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return basePath + File.separator + getTablePath(tableInfo) + outFile + ".ftl";
}
};
return fileOutConfig;
}
public static FileOutConfig initJsFileOutConfig(String templatePath, String basePath, String outFile) {
FileOutConfig fileOutConfig = new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return basePath + File.separator + getTablePath(tableInfo) + outFile + ".js";
}
};
return fileOutConfig;
}
public static FileOutConfig initMenuSQLFileOutConfig(String templatePath, String basePath) {
FileOutConfig fileOutConfig = new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return basePath + File.separator + getModulePath(tableInfo) + File.separator + tableInfo.getMapperName() + ".sql";
}
};
return fileOutConfig;
}
public static FileOutConfig initXmlFileOutConfig(String templatePath, String basePath) {
FileOutConfig fileOutConfig = new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return basePath + File.separator + getModulePath(tableInfo) + File.separator + tableInfo.getMapperName() + ".xml";
}
};
return fileOutConfig;
}
public static FileOutConfig initFileOutConfig(String templatePath, String basePath, String suffix) {
FileOutConfig fileOutConfig = new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return basePath + File.separator + tableInfo.getEntityName() + suffix;
}
};
return fileOutConfig;
}
public static FileOutConfig initApiFileOutConfig(String templatePath, String basePath, String suffix) {
FileOutConfig fileOutConfig = new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
return basePath + File.separator + tableInfo.getEntityName().toLowerCase() + suffix;
}
};
return fileOutConfig;
}
public static String getModulePath(TableInfo tableInfo) {
String[] modules = tableInfo.getName().split("_");
String moduleName = "";
for (int i = 0; i < modules.length; i++) {
if (i == 0) {
moduleName = modules[i];
break;
}
}
return moduleName;
}
public static String getTablePath(TableInfo tableInfo) {
String[] modules = tableInfo.getName().split("_");
String moduleName = "";
String otherPath = "";
for (int i = 0; i < modules.length; i++) {
if (i == 0) {
moduleName = modules[i];
} else {
otherPath = otherPath + modules[i];
}
}
return moduleName + File.separator + otherPath + File.separator;
}
}
3、需要注意的是,设计表结构是一下五项是必带的,不然生成时会报错的,如下红框圈住的字段
也可不用,但是需要在MpGenerator类中去掉设置父类
4、数据库连接需要改成,需要生成表的mysql服务器连接,然后使用MpGenerator运行即可,生成文件如下:
5、最后,可以把生成的代码,copy到自己在用的项目中,如果路径不对,改一下就可以正常使用啦
项目代码,我放到下面云盘上了,有需要的可以下载一下,可在本地运行。
链接:https://pan.baidu.com/s/1ND_yDHFgJR3ZlUAze_CbhA
提取码:jk7e
OK 就到这里啦^ - ^