utils/GenEntityMysql.java
package utils; 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.Date; 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://127.0.0.1:3306/yxyk-golo"; private static final String NAME = "root"; private static final String PASS = "123456"; private static final String DRIVER = "com.mysql.jdbc.Driver"; private String packagePath = "com.yxyk.golo.entity"; // 实体包名 private String packageOutPath = "main/java/com/yxyk/golo/entity"; // 实体生成(src目录)路径 private String authorName = "php-note.com"; // 作者名字 /** * 类的构造方法 */ private GenEntityMysql() { } /** * 生成class的所有内容 */ private String parse() { StringBuffer sb = new StringBuffer(); sb.append("package " + packagePath + ";\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/**\r\n"); sb.append(" * 表名: " + tableName + "\r\n"); sb.append(" * \r\n"); sb.append(" * @author " + authorName + "\r\n"); sb.append(" * @since " + SDF.format(new Date()) + "\r\n"); sb.append(" */ \r\n"); // 实体部分 sb.append("public class " + getTransStr(tableName, true) + " {\r\n"); processAllAttrs(sb); // 属性 processAllMethod(sb); // get set方法 sb.append("}"); return sb.toString(); } /** * 生成所有成员变量 */ private void processAllAttrs(StringBuffer sb) { for (int i = 0; i < colNames.length; i++) { sb.append(" private " + sqlType2JavaType(colTypes[i]) + " " + getTransStr(colNames[i], false) + ";\r\n"); } } /** * 生成所有get/set方法 */ private void processAllMethod(StringBuffer sb) { for (int i = 0; i < colNames.length; i++) { sb.append("\r\n public void set" + getTransStr(colNames[i], true) + "(" + sqlType2JavaType(colTypes[i]) + " " + getTransStr(colNames[i], false) + ") {\r\n"); sb.append(" this." + getTransStr(colNames[i], false) + " = " + getTransStr(colNames[i], false) + ";\r\n"); sb.append(" }\r\n\r\n"); sb.append(" public " + sqlType2JavaType(colTypes[i]) + " get" + getTransStr(colNames[i], true) + "() {\r\n"); sb.append(" return " + getTransStr(colNames[i], false) + ";\r\n"); sb.append(" }\r\n"); } } /** * 将传入字符串的首字母转成大写 */ 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); } /** * 将mysql中表名和字段名转换成驼峰形式 */ 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]); } for (int i=1; i<strs.length; i++) after.append(initCap(strs[i])); return after.toString(); } /** * 查找sql字段类型所对应的Java类型 */ 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") || sqlType.equalsIgnoreCase("INTEGER")) { return "Integer"; } 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")||sqlType.equalsIgnoreCase("timestamp")) { return "Date"; } else if (sqlType.equalsIgnoreCase("image")) { return "Blod"; } return null; } /** * 生成方法 */ 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(); // 从元数据中获取到所有的表名 ResultSet rs = db.getTables(null, null, null, new String[] { "TABLE" }); String tableSql; PrintWriter pw = null; while (rs.next()) { tableName = rs.getString(3); 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 outputPath = directory.getAbsolutePath() + "/src/" + packageOutPath + "/" + getTransStr(tableName, true) + ".java"; FileWriter fw = new FileWriter(outputPath); pw = new PrintWriter(fw); pw.println(content); pw.flush(); System.out.println("create class >>>>> " + tableName); } if (pw != null) pw.close(); } /** * 执行方法 */ public static void main(String[] args) { try { INSTANCE.generate(); System.out.println("generate classes success!"); } catch (Exception e) { e.printStackTrace(); } } }