Generating entity classes based on database tables in Java __c#

Source: Internet
Author: User
Tags datetime int size stringbuffer
Import Java.io.File;
Import java.io.IOException;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSetMetaData;

Import java.sql.SQLException;

Import Org.apache.commons.io.FileUtils;  public class Genentityutil {private string[] Colnames//column array group private string[] coltypes;//Column name type array private Int[] colsizes; Column Name Size array private Boolean f_util = false; Whether to import packages java.util.* Private Boolean f_sql = false; Do you want to import package java.sql.* public Genentityutil (String PackagePath, String tablename) {Connection conn = Databaseu Tils.openconnection ();
        Get the database connection PreparedStatement pstmt = null;
        String strSQL = "SELECT * from" + tablename;
            try {pstmt = conn.preparestatement (strSQL);
            ResultSetMetaData RSMD = Pstmt.getmetadata (); int size = Rsmd.getcolumncount ();
            Total number of columns colnames = new String[size];
            Coltypes = new String[size]; colsizes = new inT[size];  for (int i = 0; i < Rsmd.getcolumncount (); i++) {Colnames[i] = This.getcamelstr (Rsmd.getcolumnname (i +
                1));
                Coltypes[i] = rsmd.getcolumntypename (i + 1);
                if (Coltypes[i].equalsignorecase ("datetime")) {F_util = true; } if (Coltypes[i].equalsignorecase ("image") | | coltypes[i].equalsignorecase ("text"
                ) {F_sql = true;
            } Colsizes[i] = rsmd.getcolumndisplaysize (i + 1);
            	try {String content = Parse (colnames, Coltypes, colsizes, PackagePath, TableName);
                String Path = System.getproperty ("User.dir") + "/src/" + packagepath.replaceall ("\.", "/");
                File File = new file (path);
                if (!file.exists ()) {file.mkdirs ();
 String Respath = path+ "/" +initcap (tablename) + ". Java";               System.out.println ("respath=" + Respath);
            Fileutils.writestringtofile (New File (Respath), content);
            catch (IOException e) {e.printstacktrace ();
        } catch (SQLException e) {e.printstacktrace ();
        finally {databaseutils.closedatabase (conn, pstmt, NULL); }/** * Parsing processing (Generating entity class body code)/private String parse (string[] colnames, string[] coltypes, int[] Colsize
        S, String PackagePath, String tablename) {StringBuffer sb = new StringBuffer ();
        Sb.append ("package" + PackagePath + "; \r\n\r\n");
        if (f_util) {sb.append ("import java.util.date;\r\n");
        } if (F_sql) {sb.append ("import java.sql.*;\r\n\r\n\r\n");
        } sb.append ("public class" + INITCAP (tablename) + "{\r\n\r\n");
        Processallattrs (SB);
        Sb.append ("\ r \ n");
        Processallmethod (SB); Sb.append ("}\r\n");
        System.out.println (Sb.tostring ());

    return sb.tostring (); /** * Generate All methods * * @param SB */private void Processallmethod (StringBuffer sb) {for (i NT i = 0; i < colnames.length; i++) {sb.append ("\tpublic void Set" + Initcap (colnames[i)) + "(" + Sqltype2javatype (colty
            Pes[i] + "" + Colnames[i] + ") {\ r \ n");
            Sb.append ("\t\tthis." + colnames[i] + "=" + colnames[i] + "; \ n");

            Sb.append ("\t}\r\n\r\n");
            Sb.append ("\tpublic" + sqltype2javatype (coltypes[i)) + "get" + initcap (colnames[i)) + "() {\ r \ n");
            Sb.append ("\t\treturn" + colnames[i] + "; \ r \ n");
        Sb.append ("\t}\r\n\r\n"); }/** * Parse output attribute * * @return/private void Processallattrs (StringBuffer sb) {for (int i = 0; i < colnames.length; i++) {sb.append ("\tprivate" + sqltype2javatype) (ColTYpes[i]) + "" + colnames[i] + "; \ r \ n"); /** * Convert the first 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 This.getcamelstr (New String (CH));  }//Example: User_name--> userName private String getcamelstr (string s) {while (S.indexof ("_") >0) {int
			index = S.indexof ("_");
			System.out.println (S.substring (index+1, index+2). toUpperCase ());
		s = s.substring (0, index) + s.substring (index+1, index+2). toUpperCase () + s.substring (index+2);
    return s;  private string Sqltype2javatype (string sqltype) {if (Sqltype.equalsignorecase ("bit")) {return
        "BOOL";
        else if (sqltype.equalsignorecase ("tinyint")) {return "byte"; else if (sqltype.equalsignorecase ("smallint")) {Return "Short";
        else if (sqltype.equalsignorecase ("int") | | sqltype.equalsignorecase ("integer") {return "int";
        else if (sqltype.equalsignorecase ("bigint")) {return "long";
        else if (sqltype.equalsignorecase ("float")) {return "float"; else if (Sqltype.equalsignorecase ("decimal") | | sqltype.equalsignorecase ("numeric") | | s
        Qltype.equalsignorecase ("real") {return "double"; else if (sqltype.equalsignorecase ("Money") | | sqltype.equalsignorecase ("smallmoney")) {Retu
        RN "Double"; else if (sqltype.equalsignorecase ("varchar") | | sqltype.equalsignorecase ("char") | | sqlt Ype.equalsignorecase ("nvarchar") | |
        Sqltype.equalsignorecase ("nchar")) {return "String";
        else if (sqltype.equalsignorecase ("datetime")) {return "Date"; } else if (SQLType.equalsignorecase ("image") {return "Blob";
        else if (sqltype.equalsignorecase ("text")) {return "Clob";
    return null;
    	public static void Main (string[] args) {String PackagePath = "Com.test.model";
        String tablename = "Test";
    New Genentityutil (Packagepath,tablename); }
    
}
Reference article: http://qinya.iteye.com/blog/726466

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.