用Java根據資料庫表產生實體類__c#

來源:互聯網
上載者:User
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; // 列名數組    private String[] colTypes; // 列名類型數組    private int[] colSizes; // 列名大小數組    private boolean f_util = false; // 是否需要匯入包java.util.*    private boolean f_sql = false; // 是否需要匯入包java.sql.*    public GenEntityUtil(String packagePath, String tableName) {        Connection conn = DatabaseUtils.openConnection(); // 得到資料庫連接        PreparedStatement pstmt = null;        String strsql = "select * from " + tableName;        try {            pstmt = conn.prepareStatement(strsql);            ResultSetMetaData rsmd = pstmt.getMetaData();            int size = rsmd.getColumnCount(); // 共有多少列            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);        }    }    /**    * 解析處理(產生實體類主體代碼)    */    private String parse(String[] colNames, String[] colTypes, int[] colSizes, 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();    }    /**    * 產生所有的方法    *     * @param sb    */    private void processAllMethod(StringBuffer sb) {        for (int i = 0; i < colnames.length; i++) {            sb.append("\tpublic void set" + initcap(colnames[i]) + "("                    + sqlType2JavaType(colTypes[i]) + " " + colnames[i]                    + "){\r\n");            sb.append("\t\tthis." + colnames[i] + "=" + colnames[i] + ";\r\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");        }    }    /**    * 解析輸出屬性    *     * @return    */    private void processAllAttrs(StringBuffer sb) {        for (int i = 0; i < colnames.length; i++) {            sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + ";\r\n");        }    }    /**    * 把輸入字串的首字母改成大寫    *     * @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));    }        //例: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")                || sqlType.equalsIgnoreCase("real")) {            return "double";        } else if (sqlType.equalsIgnoreCase("money")                || sqlType.equalsIgnoreCase("smallmoney")) {            return "double";        } else if (sqlType.equalsIgnoreCase("varchar")                || sqlType.equalsIgnoreCase("char")                || sqlType.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);    }    }
參考文章: http://qinya.iteye.com/blog/726466

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.