mybatis plus代码生成器

package com.tycin.blog.generator;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
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.*;
import com.baomidou.mybatisplus.generator.config.converts.PostgreSqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.querys.PostgreSqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.tycin.blog.configure.Configuration;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
@Component
public class CodeGenerator {
// 常量设置
// private static String ENTITY_TEMPLATE = "";
private static Configuration configuration= new Configuration();
private static final String JAVA_OUTPUT_PATH = "/java/com/tycin/blog/";
private static final String RESOURCE_OUTPUT_PATH = "/resources/";
private static final String[] TABLES = new String[]{"t_article","t_attachment","t_collection","t_collection_type","t_permission","t_record","t_role","t_user","t_user_role","t_role_permission"};
public 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.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args){
// 代码生成器
AutoGenerator autoGenerator = new AutoGenerator();
// 全局配置
GlobalConfig globalConfig = new GlobalConfig();
// 项目路径
String projectPath = System.getProperty("user.dir");
// 设置是否覆盖已有文件
globalConfig.setFileOverride(true);
// 是否在xml中添加二级缓存配置(不推荐使用)
globalConfig.setEnableCache(false);
// 开启kotlin模式()
globalConfig.setKotlin(false);
// 开启activeRecord模式
globalConfig.setActiveRecord(true);
// 开启baseresultMap
globalConfig.setBaseResultMap(true);
// 开启baseColumnList
globalConfig.setBaseColumnList(true);
// 开启时间类型对应策略(选择TIME_PACK以便使用LocalDateTime)
globalConfig.setDateType(DateType.TIME_PACK);
// 实体命名方式
globalConfig.setEntityName("%sEntity");
// mapper命名方式
globalConfig.setMapperName("%sMapper");
// mapper xml命名方式
globalConfig.setXmlName("%sMapperXml");
// service命名方式
globalConfig.setServiceName("%sService");
// service impl 命名方式
globalConfig.setServiceImplName("%sServiceImpl");
// controller命名方式
globalConfig.setControllerName("%sController");
// 指定生成的主键ID类型
globalConfig.setIdType(IdType.ASSIGN_UUID);
// 代码生成存放目录
globalConfig.setOutputDir(projectPath + "/src/main");
// 设置作者
globalConfig.setAuthor("cjb");
// 设置是否打开输出目录
globalConfig.setOpen(false);
// 实体属性 Swagger2 注解
globalConfig.setSwagger2(true);
// 将配置导入生成器
autoGenerator.setGlobalConfig(globalConfig);

// 模版设置
// TemplateConfig templateConfig = new TemplateConfig();
// templateConfig.setEntity();
// templateConfig.setEntityKt();
// templateConfig.setService();
// templateConfig.setServiceImpl();
// templateConfig.setMapper();
// templateConfig.setXml();
// templateConfig.setController();

// 数据源配置
DataSourceConfig dataSourceConfig = new DataSourceConfig();
// 配置数据源的Url
dataSourceConfig.setUrl(configuration.getUrl());
// 配置数据源的模式(postgresql中的概念)
dataSourceConfig.setSchemaName("public");
// 配置驱动名称
dataSourceConfig.setDriverName(configuration.getDriver());
// 配置数据库用户名
dataSourceConfig.setUsername(configuration.getUsername());
// 配置数据库密码
dataSourceConfig.setPassword(configuration.getPassword());
// 配置数据库信息查询类
dataSourceConfig.setDbQuery(new PostgreSqlQuery());
// 配置数据库类型
dataSourceConfig.setDbType(DbType.POSTGRE_SQL);
// 配置类型转换
dataSourceConfig.setTypeConvert(new PostgreSqlTypeConvert());
// 将数据源配置置入生成器
autoGenerator.setDataSource(dataSourceConfig);
// 数据库表配置(策略配置)
StrategyConfig strategyConfig = new StrategyConfig();
// 驼峰转连字符
// strategyConfig.setControllerMappingHyphenStyle(false);
// 设置生成@RestController
// strategyConfig.setRestControllerStyle(true);
// 设置boolean类型字段是否移除is前缀
// strategyConfig.setEntityBooleanColumnRemoveIsPrefix(false);
// 设置实体是否生成字段常量
strategyConfig.setEntityColumnConstant(true);
// 需要包含的表名(与exclude二选一)
// strategyConfig.setInclude();
// 模糊匹配表名
// strategyConfig.setLikeTable();
// 需要排除的表名,当enableSqlFilter为false时,允许正则表达式
// strategyConfig.setExclude();
// 模糊排除表名
// strategyConfig.setNotLikeTable();
// 设置实体是否为构建者模型
// strategyConfig.setChainModel(false);
// 设置实体是否为lombok模型
strategyConfig.setEntityLombokModel(true);
// 设置生成实体类时生成字段注解
strategyConfig.setEntityTableFieldAnnotationEnable(true);
// 设置乐观锁属性名称
strategyConfig.setVersionFieldName("version");
// 设置逻辑删除属性名称
strategyConfig.setLogicDeleteFieldName("deleted");

// 设置需要生成的数据库表
strategyConfig.setInclude(TABLES);
// 设置是否大写命名
strategyConfig.setCapitalMode(true);
// 设置是否跳过视图
strategyConfig.setSkipView(true);
// 设置数据库表映射到实体的命名策略
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
// 设置数据库表字段映射到实体的命名策略(未设置按照naming执行)
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
// 设置表前缀
strategyConfig.setTablePrefix("t_");
// 设置字段前缀
// strategyConfig.setFieldPrefix("");
// 设置自定义继承的entity类全称,带包名
// strategyConfig.setSuperEntityClass("/home/tycin-deepin/Documents/gitRepos/blogsystem/blog/src/main/java/com/tycin/blog/base/BaseEntity.java");
// 自定义基础的entity类,公共字段
// strategyConfig.setSuperEntityColumns();
// 自定义继承的Mapper类全称,带包名
// strategyConfig.setSuperMapperClass();
// 自定义继承的service类全称,带包名
// strategyConfig.setSuperServiceClass();
// 自定义继承的ServiceImpl类全称,带包名
// strategyConfig.setSuperServiceImplClass();
// 自定义继承的controller类全称,带包名
// strategyConfig.setSuperControllerClass();
// 默认激活进行sql模糊表名匹配
strategyConfig.setEnableSqlFilter(false);
// 将策略配置导入生成器
autoGenerator.setStrategy(strategyConfig);

// 包配置
PackageConfig packageConfig = new PackageConfig();
// packageConfig.setModuleName(scanner("模块名"));
// 设置父包名
packageConfig.setParent("com.tycin.blog");
// 设置controller包名
packageConfig.setController("controller");
// 设置service包名
packageConfig.setService("service");
// 设置mapper包名
packageConfig.setMapper("mapper");
// 设置xml包名
packageConfig.setXml("mapper_xml");
// 设置entity包名
packageConfig.setEntity("entity");
// 设置serviceImpl包名
packageConfig.setServiceImpl("serviceImpl");
// 设置路径配置信息
HashMap<String,String> pathInfo = new HashMap<>();
pathInfo.put("entity_path",globalConfig.getOutputDir()+JAVA_OUTPUT_PATH+packageConfig.getEntity());
pathInfo.put("controller_path",globalConfig.getOutputDir()+JAVA_OUTPUT_PATH+packageConfig.getController());
pathInfo.put("xml_path",globalConfig.getOutputDir()+RESOURCE_OUTPUT_PATH+packageConfig.getXml());
pathInfo.put("service_path",globalConfig.getOutputDir()+JAVA_OUTPUT_PATH+packageConfig.getService());
pathInfo.put("service_impl_path",globalConfig.getOutputDir()+JAVA_OUTPUT_PATH+packageConfig.getServiceImpl());
pathInfo.put("mapper_path",globalConfig.getOutputDir()+JAVA_OUTPUT_PATH+packageConfig.getMapper());
packageConfig.setPathInfo(pathInfo);
// 将包设置导入生成器
autoGenerator.setPackageInfo(packageConfig);

// 自定义配置
InjectionConfig injectionConfig = new InjectionConfig() {
@Override
public void initMap() {
// todo
}
};
// 自定义输出配置
List<FileOutConfig> fileOutConfigList = new ArrayList<>();
// 自定义配置会被优先输出
// 配置实体类输出目录路径
fileOutConfigList.add(new FileOutConfig(/*ENTITY_TEMPLATE*/) {
@Override
public String outputFile(TableInfo tableInfo) {
return globalConfig.getOutputDir()+JAVA_OUTPUT_PATH+packageConfig.getEntity()
+StringPool.SLASH+tableInfo.getEntityName()+ StringPool.DOT_JAVA;
}
});
// 配置mapper xml文件输出目录路径
fileOutConfigList.add(new FileOutConfig(/*MAPPER_XML_TEMPLATE*/) {
@Override
public String outputFile(TableInfo tableInfo) {
return globalConfig.getOutputDir() + RESOURCE_OUTPUT_PATH + packageConfig.getXml()+StringPool.SLASH
+tableInfo.getMapperName() + StringPool.DOT_XML;
}
});
// 配置mapper文件输出目录路径
fileOutConfigList.add(new FileOutConfig(/*MAPPER_TEMPLATE*/) {
@Override
public String outputFile(TableInfo tableInfo) {
return globalConfig.getOutputDir() + JAVA_OUTPUT_PATH + packageConfig.getMapper() + StringPool.SLASH
+ tableInfo.getMapperName() + StringPool.DOT_JAVA;
}
});
// 配置service文件输出目录路径
fileOutConfigList.add(new FileOutConfig(/*SERVICE_TEMPLATE*/) {
@Override
public String outputFile(TableInfo tableInfo) {
return globalConfig.getOutputDir() + JAVA_OUTPUT_PATH + packageConfig.getService() + StringPool.SLASH
+ tableInfo.getServiceName() + StringPool.DOT_JAVA;
}
});
// 配置serviceImpl文件输出目录路径
fileOutConfigList.add(new FileOutConfig(/*SERVICE_IMPL_TEMPLATE*/) {
@Override
public String outputFile(TableInfo tableInfo) {
return globalConfig.getOutputDir() + JAVA_OUTPUT_PATH + packageConfig.getServiceImpl() + StringPool.SLASH
+ tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
}
});
// 配置controller文件输出目录路径
fileOutConfigList.add(new FileOutConfig(/*CONTROLLER_TEMPLATE*/) {
@Override
public String outputFile(TableInfo tableInfo) {
return globalConfig.getOutputDir() + JAVA_OUTPUT_PATH + packageConfig.getController() + StringPool.SLASH
+ tableInfo.getControllerName() + StringPool.DOT_JAVA;
}
});
// injectionConfig.setFileCreate(new IFileCreate() {
// @Override
// public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// // 判断自定义文件夹是否需要创建
// checkDir(globalConfig.getOutputDir()+RESOURCE_OUTPUT_PATH+packageConfig.getXml());
// if (fileType == FileType.MAPPER) {
// // 已经生成 mapper 文件判断存在,不想重新生成返回 false
// return !new File(filePath).exists();
// }
// // 允许生成模板文件
// return true;
// }
// });
injectionConfig.setFileOutConfigList(fileOutConfigList);
autoGenerator.setCfg(injectionConfig);
autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
autoGenerator.execute();
}
}
原文地址:https://www.cnblogs.com/linyueshaoxia/p/14033369.html