文章目录
-
目录
前言
一、导入相应的代码生成器依赖
二、使用步骤
1.在Spring boot test/java中添加
2.生成示例
总结
前言
1. MyBatis-Plus 是一个 Mybatis 增强版工具,在 MyBatis 上扩充了其他功能没有改变其基本功能,为了简化开发提交效率而存在。
2. MyBatis-Plus 的代码生成器可以生成 Entity、Mapper、Mapper XML、Service、Controller 模块代码。
3.MyBatis-Plus 的代码生成器基于Spring boot帮助代码生成(Spring boot在这里我就不做过多介绍了)
一、导入相应的代码生成器依赖
org.apache.velocity
velocity
1.7
提示:MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖,才能实现代码生成器功能。
二、使用步骤
1.在Spring boot test/java中添加
CodeGenerator类
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Data
@Accessors(chain = true)
public class CodeGenerator {
private String userName;
private String password;
private String driverName;
private String driverUrl;
private String projectPackagePath;
private String parentPackage;
private String packageController = "controller";
// ############################ 自定义配置部分 start ############################
private String moduleName;
private String projectName ="";
private String author;
private String tableName;
private String pkIdColumnName = "id";
private GeneratorStrategy generatorStrategy = GeneratorStrategy.ALL;
public enum GeneratorStrategy {
SIMPLE, NORMAL, ALL
}
private boolean pageListOrder = false;
private boolean paramValidation = true;
private boolean generatorEntity;
private boolean generatorController;
private boolean generatorService;
private boolean generatorServiceImpl;
private boolean generatorMapper;
private boolean generatorMapperXml;
private boolean generatiorEvent;
private boolean generatorListHtml;
private boolean generatorEditHtml;
private boolean generatorActivitiTable;
private boolean generatorQueryParam;
private boolean generatorQueryVo;
private boolean requiresPermissions;
// ############################ 自定义配置部分 end ############################
private String commonParentPackage;
private String mybatisParentPackage;
private String superEntity;
private String superController;
private String superService;
private String superServiceImpl;
private String superQueryParam;
private String[] superEntityCommonColumns;
// 公共类包路径
private String commonIdParam;
private String commonApiResult;
private String commonOrderEnum;
private String commonOrderQueryParam;
private String commonPaging;
private boolean fileOverride;
// 自定义需要填充的字段
private List tableFillList = new ArrayList<>();
private String[] path;
public void init() {
this.commonParentPackage = this.parentPackage + ".common";
this.mybatisParentPackage =this.parentPackage + ".mybatis";
// 父类包路径
this.superEntity = this.commonParentPackage + ".entity.baseEntity";
this.superController = this.commonParentPackage + ".controller.baseController";
this.superService = this.mybatisParentPackage + ".service.baseService";
this.superServiceImpl = this.mybatisParentPackage + ".service.impl.baseServiceImpl";
this.superQueryParam = this.mybatisParentPackage + ".param.QueryParam";
this.superEntityCommonColumns = new String[]{};
// 公共类包路径
this.commonIdParam = this.commonParentPackage + ".param.IdParam";
this.commonApiResult = this.commonParentPackage + ".api.ApiResult";
this.commonOrderEnum = this.commonParentPackage + ".enums.OrderEnum";
this.commonOrderQueryParam = this.mybatisParentPackage + ".param.OrderQueryParam";
this.commonPaging = this.mybatisParentPackage+".vo.Paging";
tableFillList.add(new TableFill("update_time",FieldFill.UPDATE));
tableFillList.add(new TableFill("update_by",FieldFill.UPDATE));
tableFillList.add(new TableFill("create_time",FieldFill.INSERT));
tableFillList.add(new TableFill("create_by",FieldFill.INSERT));
}
public void generator() {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/"+projectName+"/src/main/java");
gc.setAuthor(author);
gc.setOpen(false); // 是否打开输出目录
gc.setSwagger2(true); // 启用swagger注解
gc.setIdType(IdType.ID_WORKER); // 主键类型:ID_WORKER
gc.setServiceName("%sService"); // 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setFileOverride(fileOverride); // 是否覆盖已有文件
gc.setDateType(DateType.ONLY_DATE); // 设置日期类型为Date
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(driverUrl);
// dsc.setSchemaName("public");
dsc.setDriverName(driverName);
dsc.setUsername(userName);
dsc.setPassword(password);
// 设置自定义查询
dsc.setDbQuery(new com.sinosoft.springbootplus.mybatis.generator.config.SpringBootPlusMySqlQuery());
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(moduleName);
pc.setParent(parentPackage);
pc.setController(packageController);
pc.setService("application.service");
pc.setServiceImpl("application.service.impl");
pc.setMapper("domain.mapper");
pc.setEntity("domain.entity");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
String camelTableName = underlineToCamel(tableName);
String pascalTableName = underlineToPascal(tableName);
String colonTableName = underlineTocolon(tableName);
Map map = new HashMap<>();
map.put("customField", "Hello " + this.getConfig().getGlobalConfig().getAuthor());
// 查询参数包路径
String queryParamPackage = parentPackage + StringPool.DOT + pc.getModuleName() + ".param";
map.put("queryParamPackage", queryParamPackage);
// 查询参数类路径
map.put("queryParamPath", queryParamPackage + StringPool.DOT + pascalTableName + "QueryParam");
// 查询参数共公包路径
map.put("queryParamCommonPath", superQueryParam);
// 查询参数共公包路径
map.put("idParamPath", commonIdParam);
// 响应结果包路径
String queryVoPackage = parentPackage + StringPool.DOT + pc.getModuleName() + ".vo";
map.put("queryVoPackage", queryVoPackage);
// 响应结果类路径
map.put("queryVoPath", queryVoPackage + StringPool.DOT + pascalTableName + "QueryVo");
// 实体对象名称
map.put("entityObjectName", camelTableName);
// service对象名称
map.put("serviceObjectName", camelTableName + "Service");
// mapper对象名称
map.put("mapperObjectName", camelTableName + "Mapper");
// 主键ID列名
map.put("pkIdColumnName", pkIdColumnName);
// 主键ID驼峰名称
map.put("pkIdCamelName", underlineToCamel(pkIdColumnName));
// 导入分页类
map.put("paging", commonPaging);
// 导入排序枚举
map.put("orderEnum", commonOrderEnum);
// ApiResult
map.put("apiResult", commonApiResult);
// 分页列表查询是否排序
map.put("pageListOrder", pageListOrder);
// 导入排序查询参数类
map.put("orderQueryParamPath", commonOrderQueryParam);
// 代码生成策略
map.put("generatorStrategy", generatorStrategy);
// 代码Validation校验
map.put("paramValidation", paramValidation);
// 冒号连接的表名称
map.put("colonTableName", colonTableName);
// 是否生成Shiro RequiresPermissions注解
map.put("requiresPermissions", requiresPermissions);
//================页面生成部分(开始)========
if(generatorListHtml || generatorEditHtml){
map.put("baseLayFilter",StringUtils.join(path,"-")+"-"+camelTableName+"List");
map.put("baseEditPath",StringUtils.join(path,"/")+"/"+camelTableName+"Edit");
}
map.put("publishPackage","com.sinosoft.springbootplus."+moduleName+".application.event.publish");
map.put("pubisherClass",pascalTableName+"Pubisher");
map.put("subscriptionPackage","com.sinosoft.springbootplus."+moduleName+".application.event.subscription");
map.put("subscriptionClass",pascalTableName+"Subscription");
map.put("domainPackage","com.sinosoft.springbootplus."+moduleName+".domain.service");
map.put("domainClass",pascalTableName+"Domain");
map.put("domainClassName",camelTableName+"Domain");
//================页面生成部分(结束)========
this.setMap(map);
}
};
List focList = new ArrayList<>();
// 生成mapper xml
if (generatorMapperXml) {
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/"+projectName+"/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
}
// 自定义queryParam模板
if (generatorQueryParam) {
focList.add(new FileOutConfig("/templates/queryParam.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath +"/"+projectName+ "/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/param/" + tableInfo.getEntityName() + "QueryParam" + StringPool.DOT_JAVA;
}
});
}
// 自定义queryVo模板
if (generatorQueryVo) {
focList.add(new FileOutConfig("/templates/queryVo.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + "/"+projectName+"/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/vo/" + tableInfo.getEntityName() + "QueryVo" + StringPool.DOT_JAVA;
}
});
}
if(generatiorEvent){
focList.add(new FileOutConfig("/templates/pubisher.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + "/"+projectName+"/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/application/event/publish/" + tableInfo.getEntityName() + "Pubisher" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/subscription.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + "/"+projectName+"/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/application/event/subscription/"+ tableInfo.getEntityName() + "Subscription" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/domain.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + "/"+projectName+"/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/domain/service/" + tableInfo.getEntityName() + "Domain" + StringPool.DOT_JAVA;
}
});
}
// 自定义generatorListHtml模板
if (generatorListHtml) {
focList.add(new FileOutConfig("/templates/list.html.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
String camelTableName = underlineToCamel(tableInfo.getName());
return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "List.html";
}
});
}
// 自定义generatorListHtml模板
if (generatorEditHtml) {
focList.add(new FileOutConfig("/templates/edit.html.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
String camelTableName = underlineToCamel(tableInfo.getName());
return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "Edit.html";
}
});
}
if(generatorActivitiTable){
focList.add(new FileOutConfig("/templates/activitiList.html.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
String camelTableName = underlineToCamel(tableInfo.getName());
return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "List.html";
}
});
focList.add(new FileOutConfig("/templates/activitiList.js.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
String camelTableName = underlineToCamel(tableInfo.getName());
return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + ".js";
}
});
focList.add(new FileOutConfig("/templates/edit.html.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
String camelTableName = underlineToCamel(tableInfo.getName());
return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "Edit.html";
}
});
}
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 模版生成配置,设置为空,表示不生成
TemplateConfig templateConfig = new TemplateConfig();
// xml使用自定义输出
templateConfig.setXml(null);
// 是否生成entity
if (!generatorEntity) {
templateConfig.setEntity(null);
}
// 是否生成controller
if (!generatorController) {
templateConfig.setController(null);
}
// 是否生成service
if (!generatorService) {
templateConfig.setService(null);
}
// 是否生成serviceImpl
if (!generatorServiceImpl) {
templateConfig.setServiceImpl(null);
}
// 是否生成mapper
if (!generatorMapper) {
templateConfig.setMapper(null);
}
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass(superEntity);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setSuperControllerClass(superController);
strategy.setSuperServiceClass(superService);
strategy.setSuperServiceImplClass(superServiceImpl);
strategy.setInclude(tableName);
strategy.setSuperEntityColumns(superEntityCommonColumns);
strategy.setControllerMappingHyphenStyle(true);
//逻辑删除字段名称
strategy.setLogicDeleteFieldName("deleted");
//乐观锁
strategy.setVersionFieldName("version");
strategy.setTableFillList(tableFillList);
//strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.execute();
}
public static String underlineToCamel(String underline) {
if (StringUtils.isNotBlank(underline)) {
return NamingStrategy.underlineToCamel(underline);
}
return null;
}
public static String underlineToPascal(String underline) {
if (StringUtils.isNotBlank(underline)) {
return NamingStrategy.capitalFirst(NamingStrategy.underlineToCamel(underline));
}
return null;
}
public static String underlineTocolon(String underline) {
if (StringUtils.isNotBlank(underline)) {
String string = underline.toLowerCase();
return string.replaceAll("_", ":");
}
return null;
}
public static void main(String[] args) {
System.out.println(underlineTocolon("sys_user"));
}
}
SpringBootPlusGenerator类
public class SpringBootPlusGenerator {
public static void main(String[] args) {
CodeGenerator codeGenerator = new CodeGenerator();
// 公共配置
// 数据库配置
codeGenerator
.setUserName("root")
.setPassword("123456")
.setDriverName("com.mysql.cj.jdbc.Driver")
.setDriverUrl("jdbc:mysql://localhost:3306/spring_boot_plus?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC");
// 包信息
codeGenerator
.setProjectPackagePath("com/sinosoft/springbootplus")
.setParentPackage("com.sinosoft.springbootplus");
// 组件作者等配置
codeGenerator
.setProjectName("smartcampus")
.setModuleName("system")
.setAuthor("lh")
.setPkIdColumnName("id");
// 生成策略
codeGenerator
.setGeneratorStrategy(CodeGenerator.GeneratorStrategy.ALL)
.setPageListOrder(true)
.setParamValidation(true);
// 生成实体映射相关代码,可用于数据库字段更新
// 当数据库字段更新时,可自定义自动生成哪些那文件
codeGenerator
.setGeneratorEntity(true)
.setGeneratorQueryParam(true)
.setGeneratorQueryVo(true);
// 生成业务相关代码
codeGenerator
.setGeneratorController(true)
.setGeneratorService(true)
.setGeneratorServiceImpl(true)
.setGeneratorMapper(true)
.setGeneratorMapperXml(true)
.setGeneratorEditHtml(false)
.setGeneratorListHtml(false);
// 是否生成Shiro RequiresPermissions注解
codeGenerator.setRequiresPermissions(true);
// 是否覆盖已有文件
codeGenerator.setFileOverride(true);
// 初始化公共变量
codeGenerator.init();
// 需要生成的表数组
// xxx,yyy,zzz为需要生成代码的表名称
String[] tables = {
"sys_file_manager"
};
//如果生成html则设置html目录,aa/bb/cc =》["aa","bb","cc"]
codeGenerator.setPath(new String[]{"user","test"});
// 循环生成
for (String table : tables) {
// 设置需要生成的表名称
codeGenerator.setTableName(table);
// 生成代码
codeGenerator.generator();
}
}
还需要相应的工具磨板
提示:代码生成器是基于java代码进行生成的,填入相关信息运行SpringBootPlusGenerator类中的main方法代码就可以自动生成了
2.生成示例
提示:1.生成的包 controller domain( entity mapper) param vo xml
2.在生成的包中必须有对应的类,如果包里有类说明你生成成功了,反之则没有成功.
总结
1.代码生成器在实际开发中有强大之处,节省了我们
2.代码生成器虽然好但是也有一些弊端,要适情况而使用,避免一些不必要的麻烦



