Get the table structure primary key in the database by JDBC the type of the field and the application to generate the entity class

Source: Internet
Author: User
Tags stringbuffer

Http://www.cnblogs.com/lbangel/p/3487796.html

Package cn.test;

Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.sql.Connection;
Import Java.sql.DatabaseMetaData;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.HashMap;
Import Java.util.Map;

public class Testall {
private static String Path = "D:\\tool\\project\\dynamictable\\src\\cn\\test\\entity";
private static String Pkname = "Com.mysql.jdbc.Driver";
private static String URL = "Jdbc:mysql://192.168.1.220:3306/person";
private static string[] Classnames = new string[] {"Shipstopping",
"Arriveship", "Tblusertype"};
private static map<string, string> fktablenamesandpk = new hashmap<string, string> ();

public static void Main (string[] args) {
Test ();
}

public static void Test () {
Connection conn = null;
DatabaseMetaData metaData = null;
ResultSet rs = null;
ResultSet CRS = NULL;
try {
Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = drivermanager.getconnection (URL, "admin", "123");
String Catalog = Conn.getcatalog (); Catalog is actually the database name
MetaData = Conn.getmetadata ();
File Dirfile = new file (path);
if (!dirfile.exists ()) {
Dirfile.mkdirs ();
}
Get table
rs = Metadata.gettables (null, "%", "%", new string[] {"TABLE"});
while (Rs.next ()) {
String tablename = rs.getstring ("table_name");
String classname = getclassnamebytablename (tablename);
StringBuffer sb = new StringBuffer ();
StringBuffer sbpackage = new StringBuffer ();
Sbpackage.append ("Package cn.test.entity;\r\n\r\n");
Sbpackage.append ("Import javax.persistence.column;\r\n");
Sbpackage.append ("Import javax.persistence.entity;\r\n");
Sbpackage.append ("Import javax.persistence.generatedvalue;\r\n");
Sbpackage.append ("Import javax.persistence.id;\r\n");
Sbpackage.append ("Import javax.persistence.table;\r\n\r\n");
Sb.append ("\r\[email protected]\r\n");
Sb.append ("@Table (name = \" "+ tablename +" \ ") \ r \ n");
Sb.append ("public class" + ClassName
+ "Implements java.io.Serializable {\ r \ n");
Gets the columns of the current table
CRS = Metadata.getcolumns (null, "%", TableName, "%");
Gets the referenced table whose primary key is the foreign key of the current table
Fktablenamesandpk.clear ();
ResultSet foreignkeyresultset = metadata.getimportedkeys (catalog, NULL, tablename);
while (Foreignkeyresultset.next ()) {
String pktablenname = foreignkeyresultset.getstring ("Pktable_name"); FOREIGN key table
String fkcolumnname = foreignkeyresultset.getstring ("Fkcolumn_name"); FOREIGN key
if (!fktablenamesandpk.containskey (fkcolumnname))
Fktablenamesandpk.put (Fkcolumnname, pktablenname);
}
Foreignkeyresultset.close ();
while (Crs.next ()) {
String ColumnName = crs.getstring ("column_name");
String ColumnType = crs.getstring ("type_name");
System.out.println ("--------------------------" + ColumnType);
if (Existfkcolumn (ColumnName)) {
String fkclassname = Getclassnamebytablename (Fktablenamesandpk.get (columnname));
Sbpackage.append ("import" + Pkname + "." + fkclassname+ "; \ r \ n");
Sb.append ("\t/** */\r\n");
Sb.append ("\tprivate" + fkclassname + "+ columnname+"; \ r \ n ");
} else {
Sb.append ("\t/** */\r\n");
Sb.append ("\tprivate" + getfieldtype (ColumnType, sbpackage) + "" + ColumnName + "; \ r \ n");
}
}
Sb.append ("}");
File File = new file (dirfile, classname + ". Java");
if (file.exists ()) {
File.delete ();
}
GetTitle (Sbpackage, classname);
FileOutputStream outputstream = new FileOutputStream (file);
Outputstream.write (Sbpackage.tostring (). GetBytes ());
Outputstream.write (Sb.tostring (). GetBytes ());
Outputstream.close ();
System.out.println (classname + "create success ... ");
}
} catch (Exception e) {
E.printstacktrace (System.out);
} finally {
try {
if (null! = RS) {
Rs.close ();
}
if (null! = conn) {
Conn.close ();
}
} catch (Exception E2) {
}
}
}

/**
* Get the class name based on the table name
*
* @param tablename
* @return
*/
private static string Getclassnamebytablename (String tablename) {
String classname = getclassname (tablename);
for (String name:classnames) {
if (Name.tolowercase (). Equals (Tablename.tolowercase ())) {
classname = name;
}
}
return classname;
}

private static Boolean Existfkcolumn (String columnname) {
if (FKTABLENAMESANDPK! = null) {
if (Fktablenamesandpk.containskey (ColumnName))
return true;
}
return false;
}

/**
* Suitable for the table name is a single word, for example: The table name is Tbluser class name is Tbluser; When the table name is the user class name is user; When the surface is usertype (two words)
* When the class name is usertype, if you want to usertype, add the desired class name to the Classnames field (which is not case sensitive to the database table name).
*
* @param tablename
* @return
*/
public static string GetClassName (String tablename) {
String res = tablename.tolowercase ();
if (Tablename.startswith ("TBL")) {
Return tablename.substring (0, 4) + res.substring (4);
}
Return tablename.substring (0, 1). toUpperCase () + res.substring (1);
}

/**
* Set field type MySQL data type
*
* @param columntype
* Column type String
* @param sbpackage
* Package Package Information
* @return
*/
public static string GetFieldType (String columntype, StringBuffer sbpackage) {
/*
* Tinyblob Tinyblob byte[]
Tinytext varchar java.lang.string
Blob blob byte[]
Text varchar java.lang.string
Mediumblob Mediumblob byte[]
Mediumtext varchar java.lang.string
Longblob Longblob byte[]
Longtext varchar java.lang.string
Enum (' value1 ', ' value2 ',...) char java.lang.string
Set (' value1 ', ' value2 ',...) char java.lang.string
*/
ColumnType = Columntype.tolowercase ();
if (columntype.equals ("varchar") | | | columntype.equals ("nvarchar")
|| Columntype.equals ("char")
// || Columntype.equals ("Tinytext")
// || Columntype.equals ("text")
// || Columntype.equals ("Mediumtext")
// || Columntype.equals ("Longtext")
) {
return "String";
} else if (Columntype.equals ("Tinyblob")
|| Columntype.equals ("blob")
|| Columntype.equals ("Mediumblob")
|| Columntype.equals ("Longblob")) {
return "byte[]1111";
} else if (Columntype.equals ("datetime")
|| Columntype.equals ("date")
|| Columntype.equals ("timestamp")
|| Columntype.equals ("Time")
|| Columntype.equals ("Year")) {
Sbpackage.append ("Import java.util.date;\r\n");
return "Date";
} else if (Columntype.equals ("bit")
|| Columntype.equals ("int")
|| Columntype.equals ("tinyint")
|| Columntype.equals ("smallint")
// || Columntype.equals ("bool")
// || Columntype.equals ("Mediumint")
// || Columntype.equals ("bigint")
) {
return "int";
} else if (Columntype.equals ("float")) {
return "Float";
} else if (Columntype.equals ("double")) {
return "Double";
} else if (Columntype.equals ("decimal")) {
Sbpackage.append ("Import java.math.bigdecimal;\r\n");
return "BigDecimal";
}
return "ErrorType";
}

/**
* Set Class caption Comment
*
* @param sbpackage
* @param className
*/
public static void GetTitle (StringBuffer sbpackage, String className) {
SimpleDateFormat format = new SimpleDateFormat ("yyyy mm month DD day");
Sbpackage.append ("\r\n/**\r\n");
Sbpackage.append ("*\r\n");
Sbpackage.append ("* Title:" + className + "<br/>\r\n");
Sbpackage.append ("* Description: <br/>\r\n");
Sbpackage.append ("*\r\n");
Sbpackage.append ("* Make information: DATE:" + format.format (new Date ())
+ "name:author\r\n");
Sbpackage.append ("*\r\n");
Sbpackage.append ("* Modify information <br/>\r\n");
Sbpackage.append ("* Modification date Modified by modification of the modified content <br/>\r\n");
Sbpackage.append ("*\r\n");
Sbpackage.append ("*/\r\n");
}

}

Get the table structure primary key in the database by JDBC the type of the field and the application to generate the entity class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.