【utils】指定したmysqlデータベースのテーブルからjavaエンティティクラスを生成する
23077 ワード
開発の過程でデータベースの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
");
sb.append("\r
");
//
if (needUtil) {
sb.append("import java.util.Date;\r
");
}
if (needSql) {
sb.append("import java.sql.*;\r
");
}
//
sb.append("/**\r
");
sb.append(" * table name: " + tableName + "\r
");
sb.append(" * author name: " + authorName + "\r
");
sb.append(" * create time: " + SDF.format(new Date()) + "\r
");
sb.append(" */ \r
");
//
sb.append("public class " + getTransStr(tableName, true) + "{\r
\r
");
processAllAttrs(sb);//
sb.append("\r
");
processAllMethod(sb);// get set
sb.append("}\r
");
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
");
}
}
/**
* @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
");
sb.append("\t\tthis." + getTransStr(colNames[i], false) + "=" + getTransStr(colNames[i], false) + ";\r
");
sb.append("\t}\r
");
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + getTransStr(colNames[i], true) + "(){\r
");
sb.append("\t\treturn " + getTransStr(colNames[i], false) + ";\r
");
sb.append("\t}\r
");
}
}
/**
* @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; ireturn 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 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();
}
}
}