工程源碼下載:https://github.com/DillonPu/JavaCodeAutoGenerate
使用方法:修改自定義值,運行main方法即可。
package com.al;
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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.util.*;
public class CodeGenerate {
private static Logger log = LoggerFactory.getLogger(CodeGenerate.class);
// 固定
private static String projectPath = System.getProperty("user.dir"); // 獲取當前工程目錄
private static PackageConfig pc = new PackageConfig();
// 自定義值
private static String author = "阿來小同學";
private static String ip = "localhost";
private static String port = "3306";
private static String dbname = "al"; // 數據庫名
private static String url = "jdbc:mysql://localhost:3306/al?useUnicode=true&useSSL=false&characterEncoding=utf8";
private static String driver = "com.mysql.jdbc.Driver";
private static String username = "root";
private static String password = "root";
private static String[] dbTableNames = {}; // 無值:爲數據庫中所有表生成代碼;有值 如:{"table1","table2"},只生成數組中的表
private static String javaPackageName = "com.test"; // 頂級包名
private static String javaModuleName = "codeServer"; // 模塊名
private static String mapperPackageName = ""; // mapper文件所在包名
private static final String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 freemarker
// private static final templatePath = "/templates/mapper.xml.vm"; //如果模板引擎是 velocity
static {
url = "jdbc:mysql://"
+ip+":"
+port+"/"
+dbname+"?useUnicode=true&useSSL=false&characterEncoding=utf8";
}
/**
* 讀取控制檯內容
* @param tip 提示內容
* @return
*/
public static 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.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請輸入正確的" + tip + "!");
}
/**
* 獲取數據庫表及其字段
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Map<String, Object> getDatabaseNameToTableNameAndColumnName() throws ClassNotFoundException, SQLException {
Map<String, Object> tableNameMap = new HashMap<String, Object>();
//加載驅動
Class.forName(driver);
//獲得數據庫連接
Connection connection = DriverManager.getConnection(url, username, password);
//獲得元數據
DatabaseMetaData metaData = connection.getMetaData();
//獲得表信息
ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
while (tables.next()) {
Map<String, String> columnNameMap = new HashMap<String, String>(); //保存字段名
//獲得表名
String table_name = tables.getString("TABLE_NAME");
//通過表名獲得所有字段名
ResultSet columns = metaData.getColumns(null, null, table_name, "%");
//獲得所有字段名
while (columns.next()) {
//獲得字段名
String column_name = columns.getString("COLUMN_NAME");
//獲得字段類型
String type_name = columns.getString("TYPE_NAME");
columnNameMap.put(column_name, type_name);
}
tableNameMap.put(table_name, columnNameMap);
}
return tableNameMap;
}
/**
* 獲取數據庫所有表名
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
public static String[] getTableNames() throws SQLException, ClassNotFoundException {
Map<String, Object> map = getDatabaseNameToTableNameAndColumnName();
Set<String> tableNames = map.keySet();
log.info("數據庫表名:{}",tableNames);
String[] names = new String[tableNames.size()];
names = tableNames.toArray(names);
return names;
}
/**
* 配置完畢,運行即可,生成mybatisx 代碼
* @param args
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// 代碼生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(author);
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
dsc.setDriverName(driver);
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
pc.setParent(javaPackageName);
pc.setModuleName(javaModuleName);
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 自定義輸出配置
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// 自定義配置會被優先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設置了前後綴、此處注意 xml 的名稱會跟着發生變化!!
return projectPath + "/src/main/resources/mapper/" + mapperPackageName
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判斷自定義文件夾是否需要創建
checkDir("調用默認方法創建的目錄");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據使用的模板引擎自動識別
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// 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.setRestControllerStyle(true);
// 公共父類
// 寫於父類中的公共字段
strategy.setSuperEntityColumns("id");
String[] dbTableName = dbTableNames.length>0 ? dbTableNames : getTableNames();
strategy.setInclude(dbTableName);
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
生成代碼結構效果:
mybatis plus文檔鏈接 https://mp.baomidou.com/