根據MYSQL資料庫生成註解類mybatisSQL語句(僅包含主鍵)
阿新 • • 發佈:2018-11-19
package com; import java.io.File; import java.io.FileWriter; import java.io.IOException; 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.sql.SQLException; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GenBaseSQLMysql { private String packageOutPathEntity = "com.user.entity";// 指定實體生成所在包的路徑 private String packageOutPath = "com.user.sql";// 指定實體生成所在包的路徑 private String authorName = "linshiq";// 作者名字 private String tablename = "";// 表名 private boolean f_util = false; // 是否需要匯入包java.util.* private boolean f_sql = false; // 是否需要匯入包java.sql.* private boolean f_decimal = false; // 是否需要匯入包java.sql.* // 資料庫連線 private static final String URL = "jdbc:mysql://localhost:3306/llll"; private static final String NAME = "root"; private static final String PASS = "root"; private static final String DRIVER = "com.mysql.jdbc.Driver"; /* * 建構函式 */ public GenBaseSQLMysql() { // 建立連線 Connection con; PreparedStatement pStemt = null; try { try { Class.forName(DRIVER); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } con = DriverManager.getConnection(URL, NAME, PASS); // 獲取所有的表名 DatabaseMetaData meta = con.getMetaData(); ResultSet rs = meta.getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { System.out.println("------------------------------"); System.out.println("表名:" + rs.getString(3)); System.out.println("表所屬使用者名稱:" + rs.getString(2)); String tablename = rs.getString(3); this.tablename = tablename; // 獲取所有的主鍵 // oracle 語句 select // table_name,dbms_metadata.get_ddl('TABLE','TABLE_NAME')from // dual,user_tables where table_name='TABLE_NAME'; // TABLE_NAME為具體的表名,要求大寫 String sql_table = "SHOW CREATE TABLE " + tablename; PreparedStatement pre = con.prepareStatement(sql_table); ResultSet rs1 = pre.executeQuery(); if (rs1.next()) { // 正則匹配資料 Pattern pattern = Pattern.compile("PRIMARY KEY \\(\\`(.*)\\`\\)"); Matcher matcher = pattern.matcher(rs1.getString(2)); matcher.find(); String data = ""; try { data = matcher.group(); } catch (IllegalStateException e) { System.out.println("沒主鍵"); continue; } // 過濾對於字元 data = data.replaceAll("\\`|PRIMARY KEY \\(|\\)", ""); // 拆分字元 String[] stringArr = data.split(","); System.out.println("主鍵為:" + Arrays.toString(stringArr)); System.out.println("------------------------------"); // 查要生成實體類的表 String sql = "select * from " + tablename; pStemt = con.prepareStatement(sql); ResultSetMetaData rsmd = pStemt.getMetaData(); int size = rsmd.getColumnCount(); // 統計列 String[] colnames = new String[size]; String[] colTypes = new String[size]; int[] colSizes = new int[size]; for (int i = 0; i < size; i++) { colnames[i] = rsmd.getColumnName(i + 1).toLowerCase(); colTypes[i] = rsmd.getColumnTypeName(i + 1); colSizes[i] = rsmd.getColumnDisplaySize(i + 1); } String content = parse(colnames, colTypes, colSizes, stringArr); try { File directory = new File(""); // System.out.println("絕對路徑:"+directory.getAbsolutePath()); // System.out.println("相對路徑:"+directory.getCanonicalPath()); String path = this.getClass().getResource("").getPath(); System.out.println(path); System.out.println("src/?/" + path.substring(path.lastIndexOf("/com/", path.length()))); // String outputPath = directory.getAbsolutePath()+ // "/src/"+path.substring(path.lastIndexOf("/com/", // path.length()), path.length()) + initcap(tablename) + // ".java"; String outputPath = directory.getAbsolutePath() + "/src/main/java/" + this.packageOutPath.replace(".", "/") + "/" + initcap(tablename) + "Dao.java"; FileWriter fw = new FileWriter(outputPath); System.out.println(outputPath); PrintWriter pw = new PrintWriter(fw); pw.println(content); pw.flush(); pw.close(); } catch (IOException e) { e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } finally { // try { // con.close(); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } } /** * 功能:生成實體類主體程式碼 * * @param colnames * @param colTypes * @param colSizes * @param stringArr * @return */ private String parse(String[] colnames, String[] colTypes, int[] colSizes, String[] stringArr) { // 確定匯入包 for (int i = 0; i < stringArr.length; i++) { for (int j = 0; j < colnames.length; j++) { if (colnames[j].equalsIgnoreCase(stringArr[i])) { if (colTypes[i].equalsIgnoreCase("datetime")) { f_util = true; } if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")) { f_sql = true; } String clone = colTypes[i].toLowerCase(); if (clone.contains("decimal")) { f_decimal = true; } } } } StringBuffer sb = new StringBuffer(); sb.append("package " + this.packageOutPath + ";\r\n"); sb.append("\r\n"); // 判斷是否匯入工具包 if (f_util) { sb.append("import java.util.Date;\r\n"); } if (f_sql) { sb.append("import java.sql.*;\r\n"); } if (f_decimal) { sb.append("import java.math.BigDecimal;\r\n"); } sb.append("import org.apache.ibatis.annotations.Delete;\r\n"); sb.append("import org.apache.ibatis.annotations.Insert;\r\n"); sb.append("import org.apache.ibatis.annotations.Select;\r\n"); sb.append("import org.apache.ibatis.annotations.Update;\r\n"); sb.append("import org.apache.ibatis.annotations.Mapper;\r\n"); sb.append("import " + packageOutPathEntity + "." + initcap(tablename) + ";\r\n"); sb.append("\r\n"); // 註釋部分 sb.append(" /**\r\n"); sb.append(" * " + tablename + " 基礎SQL\r\n"); sb.append(" * " + new Date() + " " + this.authorName + "\r\n"); sb.append(" */ \r\n"); // 實體部分 sb.append("\r\
[email protected]"); sb.append("\r\npublic interface " + initcap(tablename) + "Dao{\r\n"); processDelete(sb, colnames, colTypes, colSizes, stringArr); sb.append("\r\n"); processUpdate(sb, colnames, colTypes, colSizes, stringArr); sb.append("\r\n"); processSelect(sb, colnames, colTypes, colSizes, stringArr); sb.append("\r\n"); processInsert(sb, colnames, colTypes, colSizes, stringArr); sb.append("}\r\n"); // System.out.println(sb.toString()); return sb.toString(); } /** * @Author linshiq * <p> * <li>2018年11月15日-下午4:33:28</li> * <li>功能說明:補充基礎Insert</li> * </p> * @param sb * @param colnames * @param colTypes * @param colSizes * @param stringArr */ private void processInsert(StringBuffer sb, String[] colnames, String[] colTypes, int[] colSizes, String[] stringArr) { StringBuffer insertInfoSb = new StringBuffer(); for (int i = 0; i < colnames.length; i++) {// 補充insert into部分 insertInfoSb.append(colnames[i].toLowerCase()).append(","); } insertInfoSb.delete(insertInfoSb.length() - 1, insertInfoSb.length()); StringBuffer valuesSb = new StringBuffer(); // 補充values部分 for (int j = 0; j < colnames.length; j++) { valuesSb.append("#{" + colnames[j] + "}").append(","); } valuesSb.delete(valuesSb.length() - 1, valuesSb.length()); // 開始組裝 StringBuffer overParm = new StringBuffer(); overParm.append("INSERT INTO " + tablename + " ( " + insertInfoSb.toString() + " ) "); overParm.append(" VALUES (" + valuesSb.toString() + ")"); sb.append("\t" + "@Insert(\"" + overParm.toString() + "\")" + "\r\n");// 補充方法註解 sb.append("\tint insertByKey(" + initcap(tablename) + " " + tablename + ");\r\n"); //System.out.println(parm); } /** * @Author linshiq * <p> * <li>2018年11月15日-下午4:33:26</li> * <li>功能說明:補充基礎Select</li> * </p> * @param sb * @param colnames * @param colTypes * @param colSizes * @param stringArr */ private void processSelect(StringBuffer sb, String[] colnames, String[] colTypes, int[] colSizes, String[] stringArr) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < colnames.length; i++) { resultSb.append(colnames[i].toLowerCase()).append(","); } resultSb.delete(resultSb.length() - 1, resultSb.length()); StringBuffer inParm = new StringBuffer(); StringBuffer overParm = new StringBuffer(); overParm.append("SELECT " + resultSb.toString() + " FROM " + tablename + " WHERE "); for (int i = 0; i < stringArr.length; i++) { for (int j = 0; j < colnames.length; j++) { if (colnames[j].equalsIgnoreCase(stringArr[i])) { inParm.append(sqlType2JavaType(colTypes[i]) + " " + stringArr[i] + ","); overParm.append(stringArr[i] + " = " + "#{" + stringArr[i] + "}").append(" and "); } } } overParm.delete(overParm.length() - 5, overParm.length()); sb.append("\t" + "@Select(\"" + overParm.toString() + "\")" + "\r\n"); inParm.delete(inParm.length() - 1, inParm.length()); sb.append("\t" + initcap(tablename) + " selectByKey(" + inParm.toString() + ");\r\n"); //System.out.println(parm); } /** * @Author linshiq * <p> * <li>2018年11月15日-下午4:33:24</li> * <li>功能說明:補充基礎Update</li> * </p> * @param sb * @param colnames * @param colTypes * @param colSizes * @param stringArr */ private void processUpdate(StringBuffer sb, String[] colnames, String[] colTypes, int[] colSizes, String[] stringArr) { // 組裝set部分 StringBuffer setSb = new StringBuffer(); List<String> mainKey = Arrays.asList(stringArr); for (int j = 0; j < colnames.length; j++) { if (mainKey.contains(colnames[j].toUpperCase()) || mainKey.contains(colnames[j].toLowerCase())) { continue; } setSb.append(colnames[j] + " = " + "#{" + colnames[j] + "}").append(","); } // 如果小於等於0說明都是主鍵 if(setSb.length() <= 0){ return; } setSb.delete(setSb.length() - 1, setSb.length()); // 組裝where StringBuffer whereSb = new StringBuffer(); for (int i = 0; i < stringArr.length; i++) { whereSb.append(stringArr[i] + " = " + "#{" + stringArr[i].toLowerCase() + "}").append(" and "); } whereSb.delete(whereSb.length() - 5, whereSb.length()); StringBuffer overParm = new StringBuffer(); overParm.append("UPDATE " + tablename + " SET " + setSb.toString() + " WHERE "+whereSb.toString()); sb.append("\t" + "@Update(\"" + overParm.toString() + "\")" + "\r\n"); sb.append("\tint updateByKey(" + initcap(tablename) + " " + tablename + ");\r\n"); } /** * @Author linshiq * <p> * <li>2018年11月15日-下午4:13:47</li> * <li>功能說明:補充基礎刪除方法</li> * </p> * @param sb */ private void processDelete(StringBuffer sb, String[] colnames, String[] colTypes, int[] colSizes, String[] stringArr) { StringBuffer inParm = new StringBuffer();// 組裝入參 StringBuffer deleteSql = new StringBuffer(); deleteSql.append("DELETE FROM " + tablename + " WHERE "); for (int i = 0; i < stringArr.length; i++) { for (int j = 0; j < colnames.length; j++) { if (colnames[j].equalsIgnoreCase(stringArr[i])) { inParm.append(sqlType2JavaType(colTypes[i]) + " " + stringArr[i] + ","); deleteSql.append(stringArr[i] + " = " + "#{" + stringArr[i] + "}").append(" and "); // 組裝主鍵限制 } } } deleteSql.delete(deleteSql.length() - 5, deleteSql.length()); sb.append("\t" + "@Delete(\"" + deleteSql.toString() + "\")" + "\r\n"); inParm.delete(inParm.length() - 1, inParm.length()); sb.append("\t" + "int deleteByKey(" + inParm.toString() + ");\r\n"); //System.out.println(parm); } /** * 功能:將輸入字串的首字母改成大寫 * * @param str * @return */ private String initcap(String str) { char[] ch = str.toCharArray(); if (ch[0] >= 'a' && ch[0] <= 'z') { ch[0] = (char) (ch[0] - 32); } // for (int i = 1; i < ch.length; i++) { // // if (ch[i] >= 'a' && ch[i] <= 'z') { // ch[i] = (char) (ch[i] + 32); // } // } return new String(ch); } /** * 功能:獲得列的資料型別 * * @param sqlType * @return */ private String sqlType2JavaType(String sqlType) { // System.out.println(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("numeric") || sqlType.equalsIgnoreCase("real")) { return "double"; } else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney")) { return "BigDecimal"; } else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("text")) { return "String"; } else if (sqlType.equalsIgnoreCase("datetime") || sqlType.equalsIgnoreCase("timestamp")) { return "Date"; } else if (sqlType.equalsIgnoreCase("image")) { return "Blod"; } else { String clone = sqlType.toLowerCase(); if (clone.contains("decimal")) { return "BigDecimal"; } return null; } } /** * 出口 TODO * * @param args */ public static void main(String[] args) { new GenBaseSQLMysql(); } }