1. 程式人生 > >【utils】將指定的mysql資料庫中的表生成java實體類

【utils】將指定的mysql資料庫中的表生成java實體類

開發的過程中需要將資料庫中的database中的tables和java中的物件一一對應,如果自己寫很麻煩,藉助小程式可以快速生成
mysql驅動包推薦 5.1.38 版本,用6以上版本有點問題。
自己開發的ORM框架:karma-orm,只是一個簡單的DEMO級別的,只是自己學習練手的時候做的。

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import
java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class GenEntityMysql { private static final GenEntityMysql INSTANCE = new
GenEntityMysql(); private String tableName;// 表名 private String[] colNames; // 列名陣列 private String[] colTypes; // 列名型別陣列 private int[] colSizes; // 列名大小陣列 private boolean needUtil = false; // 是否需要匯入包java.util.* private boolean needSql = false; // 是否需要匯入包java.sql.* private static final
SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static final String SQL = "SELECT * FROM ";// 資料庫操作 // TODO 需要修改的地方 private static final String URL = "jdbc:mysql://localhost:3306/dbName"; private static final String NAME = "root"; private static final String PASS = "123456"; private static final String DRIVER = "com.mysql.jdbc.Driver"; private String packageOutPath = "com.test.entity";// 指定實體生成所在包的路徑 private String authorName = "paul";// 作者名字 private String[] generateTables = null;//指定需要生成的表的表名,全部生成設定為null /** * 類的構造方法 */ private GenEntityMysql() { } /** * @return * @description 生成class的所有內容 * @author paul * @date 2017年8月18日 下午5:30:07 * @update 2017年8月18日 下午5:30:07 * @version V1.0 */ private String parse() { StringBuffer sb = new StringBuffer(); sb.append("package " + packageOutPath + ";\r\n"); sb.append("\r\n"); // 判斷是否匯入工具包 if (needUtil) { sb.append("import java.util.Date;\r\n"); } if (needSql) { sb.append("import java.sql.*;\r\n"); } // 註釋部分 sb.append("/**\r\n"); sb.append(" * table name: " + tableName + "\r\n"); sb.append(" * author name: " + authorName + "\r\n"); sb.append(" * create time: " + SDF.format(new Date()) + "\r\n"); sb.append(" */ \r\n"); // 實體部分 sb.append("public class " + getTransStr(tableName, true) + "{\r\n\r\n"); processAllAttrs(sb);// 屬性 sb.append("\r\n"); processAllMethod(sb);// get set方法 sb.append("}\r\n"); return sb.toString(); } /** * @param sb * @description 生成所有成員變數 * @author paul * @date 2017年8月18日 下午5:15:04 * @update 2017年8月18日 下午5:15:04 * @version V1.0 */ private void processAllAttrs(StringBuffer sb) { for (int i = 0; i < colNames.length; i++) { sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + getTransStr(colNames[i], false) + ";\r\n"); } } /** * @param sb * @description 生成所有get/set方法 * @author paul * @date 2017年8月18日 下午5:14:47 * @update 2017年8月18日 下午5:14:47 * @version V1.0 */ private void processAllMethod(StringBuffer sb) { for (int i = 0; i < colNames.length; i++) { sb.append("\tpublic void set" + getTransStr(colNames[i], true) + "(" + sqlType2JavaType(colTypes[i]) + " " + getTransStr(colNames[i], false) + "){\r\n"); sb.append("\t\tthis." + getTransStr(colNames[i], false) + "=" + getTransStr(colNames[i], false) + ";\r\n"); sb.append("\t}\r\n"); sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + getTransStr(colNames[i], true) + "(){\r\n"); sb.append("\t\treturn " + getTransStr(colNames[i], false) + ";\r\n"); sb.append("\t}\r\n"); } } /** * @param str 傳入字串 * @return * @description 將傳入字串的首字母轉成大寫 * @author paul * @date 2017年8月18日 下午5:12:12 * @update 2017年8月18日 下午5:12:12 * @version V1.0 */ private String initCap(String str) { char[] ch = str.toCharArray(); if (ch[0] >= 'a' && ch[0] <= 'z') ch[0] = (char) (ch[0] - 32); return new String(ch); } /** * @return * @description 將mysql中表名和欄位名轉換成駝峰形式 * @author paul * @date 2017年8月18日 下午4:55:07 * @update 2017年8月18日 下午4:55:07 * @version V1.0 */ private String getTransStr(String before, boolean firstChar2Upper) { //不帶"_"的字串,則直接首字母大寫後返回 if (!before.contains("_")) return firstChar2Upper ? initCap(before) : before; String[] strs = before.split("_"); StringBuffer after = null; if (firstChar2Upper) { after = new StringBuffer(initCap(strs[0])); } else { after = new StringBuffer(strs[0]); } if (strs.length > 1) { for (int i=1; i<strs.length; i++) after.append(initCap(strs[i])); } return after.toString(); } /** * @return * @description 查詢sql欄位型別所對應的Java型別 * @author paul * @date 2017年8月18日 下午4:55:41 * @update 2017年8月18日 下午4:55:41 * @version V1.0 */ private String sqlType2JavaType(String sqlType) { if (sqlType.equalsIgnoreCase("bit")) { return "boolean"; } else if (sqlType.equalsIgnoreCase("tinyint")) { return "byte"; } else if (sqlType.equalsIgnoreCase("smallint")) { return "short"; } else if (sqlType.equalsIgnoreCase("int")) { return "int"; } else if (sqlType.equalsIgnoreCase("bigint")) { return "long"; } else if (sqlType.equalsIgnoreCase("float")) { return "float"; } else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric") || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney")) { return "double"; } else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("text")) { return "String"; } else if (sqlType.equalsIgnoreCase("datetime")) { return "Date"; } else if (sqlType.equalsIgnoreCase("image")) { return "Blod"; } return null; } /** * * @description 生成方法 * @author paul * @date 2017年8月18日 下午2:04:20 * @update 2017年8月18日 下午2:04:20 * @version V1.0 * @throws Exception */ private void generate() throws Exception { //與資料庫的連線 Connection con; PreparedStatement pStemt = null; Class.forName(DRIVER); con = DriverManager.getConnection(URL, NAME, PASS); System.out.println("connect database success..."); //獲取資料庫的元資料 DatabaseMetaData db = con.getMetaData(); //是否有指定生成表,有指定則直接用指定表,沒有則全表生成 List<String> tableNames = new ArrayList<>(); if (generateTables == null) { //從元資料中獲取到所有的表名 ResultSet rs = db.getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) tableNames.add(rs.getString(3)); } else { for (String tableName : generateTables) tableNames.add(tableName); } String tableSql; PrintWriter pw = null; for (int j = 0; j < tableNames.size(); j++) { tableName = tableNames.get(j); tableSql = SQL + tableName; pStemt = con.prepareStatement(tableSql); ResultSetMetaData rsmd = pStemt.getMetaData(); int size = rsmd.getColumnCount(); colNames = new String[size]; colTypes = new String[size]; colSizes = new int[size]; //獲取所需的資訊 for (int i = 0; i < size; i++) { colNames[i] = rsmd.getColumnName(i + 1); colTypes[i] = rsmd.getColumnTypeName(i + 1); if (colTypes[i].equalsIgnoreCase("datetime")) needUtil = true; if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")) needSql = true; colSizes[i] = rsmd.getColumnDisplaySize(i + 1); } //解析生成class的所有內容 String content = parse(); //輸出生成檔案 File directory = new File(""); String dirName = directory.getAbsolutePath() + "/src/main/java/" + packageOutPath.replace(".", "/"); File dir = new File(dirName); if (!dir.exists() && dir.mkdirs()) System.out.println("generate dir 【" + dirName + "】"); String javaPath = dirName + "/" + getTransStr(tableName, true) + ".java"; FileWriter fw = new FileWriter(javaPath); pw = new PrintWriter(fw); pw.println(content); pw.flush(); System.out.println("create class 【" + tableName + "】"); } if (pw != null) pw.close(); } /** * @param args * @description 執行方法 * @author paul * @date 2017年8月18日 下午2:03:35 * @update 2017年8月18日 下午2:03:35 * @version V1.0 */ public static void main(String[] args) { try { INSTANCE.generate(); System.out.println("generate classes success!"); } catch (Exception e) { e.printStackTrace(); } } }