pom文件添加:
<properties>
<mybatis-plus-boot-starter.version>3.3.2</mybatis-plus-boot-starter.version>
<mybatis-plus-generator.version>3.3.2</mybatis-plus-generator.version>
<freemarker.version>2.3.29</freemarker.version>
</properties>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-generator.version}</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
代码如下:
package com.knodi.common;
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.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* desc:MybatisPlus自动生成器,生成的model最好自己格式化一下
*
* @author gy
* @date 2020/4/21
*/
public class MybatisPlusGenerator {
public static void main(String[] args) {
String url = "jdbc:mysql://10.110.152.175:3306/custom?useUnicode=true&useSSL=false&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
String username = "custom";
String password = "custom";
// 数据库名
String database = "custom";
// 工程里main文件地址,如果是多模块,需要带模块的路径,例如有个叫server的module模块:server/src/main
String mainPath = "custom/src/main";
// main路径下的包名,代码会生成到此包下
String parentPackage = "com.knodi.custom";
// 要去掉的表名的前缀,没有可以传null
String tablePrefix = null;
// 要生成的table表名
String[] tables = new String[]{"table1", "table2"};
// 指定数据库表名生成代码
//generate(url, username, password, mainPath, parentPackage, tablePrefix, tables);
// 指定数据库生成该库下所有表相关的代码
generate(url, username, password, database, mainPath, parentPackage, tablePrefix);
}
private static final String XML_BEGIN = "<!-- ## 这里的代码不会被生成器覆盖 begin ## -->";
private static final String XML_END = "<!-- ## 这里的代码不会被生成器覆盖 end ## -->";
private static final String JAVA_BEGIN = "/* ## 这里的代码不会被生成器覆盖 begin ## */";
private static final String JAVA_END = "/* ## 这里的代码不会被生成器覆盖 end ## */";
public static final String XML_SUFFIX = ".xml";
public static void generate(String url, String username, String password, String database, String mainPath, String parentPackage, String tablePrefix) {
try (Connection conn = DriverManager.getConnection(url, username, password);
Statement stat = conn.createStatement();
) {
String tableQuery = "SELECT TABLE_NAME FROM information_schema.`TABLES` WHERE TABLE_SCHEMA = '" + database + "';";
List<String> tableList = new ArrayList<>();
ResultSet tableSet = stat.executeQuery(tableQuery);
while (tableSet.next()) {
tableList.add(tableSet.getString(1));
}
generate(url, username, password, mainPath, parentPackage, tablePrefix, tableList.toArray(new String[tableList.size()]));
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("AlibabaMethodTooLong")
public static void generate(String url, String username, String password, String mainPath, String parentPackage, String tablePrefix, String[] tables) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/" + mainPath + "/java");
// 设置用户名
gc.setAuthor("MybatisPlusGenerator");
gc.setOpen(true);
// service 命名方式
gc.setServiceName("%sManager");
// service impl 命名方式
gc.setServiceImplName("%sManagerImpl");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sDao");
gc.setXmlName("%sMapper");
gc.setActiveRecord(true);
// XML 二级缓存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columnList
gc.setBaseColumnList(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(parentPackage);
pc.setEntity("model");
pc.setMapper("dao");
pc.setService("manager");
pc.setServiceImpl("manager.impl");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/" + mainPath + "/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
Map<String, String> fileMap = new HashMap<>(16);
cfg.setFileCreate((configBuilder, fileType, filePath) -> {
//否则先判断文件是否存在
File file = new File(filePath);
boolean exist = file.exists();
if (!exist) {
file.getParentFile().mkdirs();
}
//如果是Entity则直接返回true表示写文件
if (fileType == FileType.ENTITY || fileType == FileType.OTHER) {
String custom = "";
if (exist) {
try {
BufferedReader in = new BufferedReader(new FileReader(filePath));
StringBuilder stringBuilder = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
stringBuilder.append(str + "\n");
}
if (fileType == FileType.ENTITY) {
if ((stringBuilder.indexOf(JAVA_BEGIN) > -1)) {
custom = "\n\t" + stringBuilder.substring(stringBuilder.indexOf(JAVA_BEGIN), stringBuilder.indexOf(JAVA_END) + JAVA_END.length());
}
} else {
if ((stringBuilder.indexOf(XML_BEGIN) > -1)) {
custom = "\n\t" + stringBuilder.substring(stringBuilder.indexOf(XML_BEGIN), stringBuilder.indexOf(XML_END) + XML_END.length());
}
}
} catch (IOException e) {
}
}
if (!exist || "".equals(custom)) {
if (fileType == FileType.ENTITY) {
custom = "\n\t" + JAVA_BEGIN + "\n\n\t" + JAVA_END;
} else {
custom = "\n\t" + XML_BEGIN + "\n\n\t" + XML_END;
}
}
fileMap.put(filePath, custom);
return true;
}
//文件不存在或者全局配置的fileOverride为true才写文件
return !exist || configBuilder.getGlobalConfig().isFileOverride();
});
mpg.setCfg(cfg);
TemplateConfig templateConfig = new TemplateConfig();
//不生成生成controller,需要的话注释掉下面一行代码
templateConfig.setController("");
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setEntityTableFieldAnnotationEnable(true);
// 指定生成的bean的数据库表名
strategy.setInclude(tables);
//去掉前缀
if (StringUtils.isNotBlank(tablePrefix)) {
strategy.setTablePrefix(tablePrefix);
}
// 驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
fileMap.forEach((f, s) -> {
try {
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder stringBuilder = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
stringBuilder.append(str + "\n");
}
if (f.endsWith(XML_SUFFIX)) {
stringBuilder.replace(stringBuilder.lastIndexOf("</mapper>"), stringBuilder.length(), s + "\n</mapper>");
} else {
stringBuilder.replace(stringBuilder.lastIndexOf("}"), stringBuilder.length(), s + "\n}");
}
BufferedWriter writer = new BufferedWriter(new FileWriter(f));
writer.write(stringBuilder.toString());
writer.close();
} catch (IOException e) {
}
});
}
}