Java automatic generation of bean tools

Source: Internet
Author: User

Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSetMetaData;
Import java.sql.SQLException;

/**
* database table converted to JavaBean object gadget (has been used for a long time),
* 1 Bean properties are underlined by the original database field, and the first letter is processed in uppercase and so on.
* 2 The generated bean has a field description for the database.
* 3 You can modify this tool to use the project.
*/
public class Myentityutils {
Private String tablename = "";
Private string[] colnames;
Private string[] coltypes;
Private int[] colsizes; Column name Size
Private int[] Colscale; Column name Decimal precision
Private Boolean importutil = false;
Private Boolean importsql = false;
Private Boolean importmath = false;

/**
* @param args
* Everyone, according to their own
*/
public void tabletoentity (String tname) {
tablename = Tname;
Data even connection get, do it yourself.
Connection conn = null;
String strSQL = "SELECT * from" + tablename;//+ "WHERE rownum=1" reads a row of records;
try {
System.out.println (strSQL);
PreparedStatement pstmt = conn.preparestatement (strSQL);
Pstmt.executequery ();
ResultSetMetaData RSMD = Pstmt.getmetadata ();
int size = Rsmd.getcolumncount (); How many columns are there?
Colnames = new String[size];
Coltypes = new String[size];
colsizes = new Int[size];
Colscale = new Int[size];
for (int i = 0; i < Rsmd.getcolumncount (); i++) {
Rsmd.getcatalogname (i + 1);
Colnames[i] = rsmd.getcolumnname (i + 1). toLowerCase ();
Coltypes[i] = rsmd.getcolumntypename (i + 1). toLowerCase ();
Colscale[i] = Rsmd.getscale (i + 1);
System.out.println (Rsmd.getcatalogname (i+1));
if ("datetime". Equals (Coltypes[i])) {
Importutil = true;
}
if ("image". Equals (Coltypes[i]) | | "Text". Equals (Coltypes[i])) {
Importsql = true;
}
if (colscale[i]>0) {
Importmath = true;
}
Colsizes[i] = rsmd.getprecision (i + 1);
}
String content = Parse (colnames, coltypes, colsizes);
try {
FileWriter FW = new FileWriter (Initcap (tablename) + ". Java");
PrintWriter pw = new PrintWriter (FW);
PW.PRINTLN (content);
Pw.flush ();
Pw.close ();
} catch (IOException e) {
E.printstacktrace ();
}
} catch (SQLException e) {
E.printstacktrace ();
} finally {
try {
if (conn!=null) conn.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
}
}

/**
* Parse processing (Generate entity class body code)
*/
Private String Parse (string[] colnames, string[] coltypes, int[] colsizes) {
StringBuffer sb = new StringBuffer ();
Sb.append ("\r\nimport java.io.serializable;\r\n");
if (importutil) {
Sb.append ("Import java.util.date;\r\n");
}
if (importsql) {
Sb.append ("Import java.sql.*;\r\n\r\n");
}
if (Importmath) {
Sb.append ("Import java.math.*;\r\n\r\n");
}
Table notes
Processcolnames (SB);
Sb.append ("public class" + INITCAP (tablename) + "implements Serializable {\ r \ n");
Processallattrs (SB);
Processallmethod (SB);
Sb.append ("}\r\n");
System.out.println (Sb.tostring ());
return sb.tostring ();

}
/**
* Handle column names, remove blank underline ' _ ', and capitalize the first letter underlined
* If the whole column is 3 characters or less, then the ' _ ' is removed and the first letter of "_" is not capitalized.
* The database column name and column type are also written in comments for viewing.
* @param SB
*/
private void Processcolnames (StringBuffer sb) {
Sb.append ("\r\n/**" + tablename + "\ r \ n");
String colsiz= "";
String colsca= "";
for (int i = 0; i < colnames.length; i++) {
Colsiz = colsizes[i]<=0? "": (colscale[i]<=0? ") ("+colsizes[i]+") ":" ("+colsizes[i]+", "+colscale[i]+") ");
Sb.append ("\ T" + colnames[i].touppercase () + "" +coltypes[i].touppercase () + colsiz+ "\ r \ n");
char[] ch = colnames[i].tochararray ();
char c = ' a ';
if (ch.length>3) {
for (int j=0;j <ch.length; J + +) {
c = Ch[j];
if (c = = ' _ ') {
if (ch[j+1]>= ' a ' && ch[j+1] <= ' z ') {
Ch[j+1]= (char) (CH[J+1]-32);
}
}
}
}
String str = new string (CH);
Colnames[i] = Str.replaceall ("_", "");
}
Sb.append ("*/\r\n");
}
/**
* Generate all the methods
*
* @param SB
*/
private void Processallmethod (StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
Sb.append ("\tpublic void Set" + Initcap (Colnames[i]) + "("
+ Oraclesqltype2javatype (Coltypes[i],colscale[i],colsizes[i]) + "" + colnames[i]
+ ") {\ r \ n");
Sb.append ("\t\tthis." + colnames[i] + "=" + colnames[i] + "; \ r \ n");
Sb.append ("\t}\r\n");

Sb.append ("\tpublic" + oraclesqltype2javatype (Coltypes[i],colscale[i],colsizes[i]) + "Get"
+ Initcap (Colnames[i]) + "() {\ r \ n");
Sb.append ("\t\treturn" + colnames[i] + "; \ r \ n");
Sb.append ("\t}\r\n");
}
}

/**
* Parse Output properties
*
* @return
*/
private void Processallattrs (StringBuffer sb) {
Sb.append ("\tprivate static final long serialversionuid = 1l;\r\n");
for (int i = 0; i < colnames.length; i++) {
Sb.append ("\tprivate" + oraclesqltype2javatype (Coltypes[i],colscale[i],colsizes[i]) + ""
+ colnames[i] + "; \ r \ n");
}
Sb.append ("\ r \ n");
}

/**
* Change the initial letter of the input string to uppercase
* @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);
}
return new String (CH);
}

/**
* Oracle
* @param sqltype
* @param scale
* @return
*/
Private String Oraclesqltype2javatype ( String sqltype, int scale,int size) {
if (sqltype.equals ("integer")) {
return "integer";
} else if (Sqltype.equa LS ("long")) {
return "long";
} else if (Sqltype.equals ("float")
| | sqltype.equals ("float precision")
| | Sqltype.equals ("double")
| | sqltype.equals ("double precision")
) {
return ' BigDecimal ';
} else if (sqltype.equals ("number")
| | Sqltype.equals ("decimal")
| | sqltype.equals ("numeric")
| | sqltype.equals ("real") {
return scale==0? (size<10?) "Integer": "Long"): "BigDecimal";
}else if (sqltype.equals ("varchar")
| | sqltype.equals ("VARCHAR2")
| | sqltype.equals ("char")
| | Sqltype.equals ("nvarchar")
| | sqltype.equals ("nchar") {
return "String";
} else if (Sqltype.equals (" DateTime ")
| | sqltype.equals (" date ")
| | sqltype.equals (" timestamp ")) {
return ' date ';
}
return null;
}

/**
* @param args
*/
public static void Main (string[] args) {
Myentityutils t = new myentityutils ();
T.tabletoentity ("TABLE");
}

}

Java automatic generation of bean tools

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.