1. 程式人生 > >mysql 自動生產java 實體類指令碼

mysql 自動生產java 實體類指令碼

mysql有表了,但是要建實體類,都是重複性工作,比較浪費時間,於是有了自動生成實體類的想法。如果用mybatis generator,會生成很多沒必要的程式碼,而且很多,看起來更亂了,實際執行的sql,比普通的增刪查改要複雜,生成的sql也其實沒什麼用,實體類還比較有用,於是只要生成實體類。
本文參考改寫自:https://blog.csdn.net/zhum_sjz/article/details/80343549 非常感謝。加上了下劃線轉駝峰和lombok。
本文用的是lombok,如果不用lombok,稍微修改下程式碼即可。如果需要加入什麼包,設定就可以了。

package com.pydt.fgw.core;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 從資料庫表反射出實體類,自動生成實體類
 *
 * @author fangshetian
 *
 */
public class SqlHelper {
    //基本資料配置
    private String packageOutPath = "com.pydt.fgw.core.model";// 指定實體生成所在包的路徑
    private String authorName = "fangsht";// 作者名字
    private String tablename = "xxx";// 表名
    private String[] colnames; // 列名陣列
    private String[] colTypes; // 列名型別陣列
    private String version = "V0.01"; // 版本
    private int[] colSizes; // 列名大小陣列
    private boolean f_util = false; // 是否需要匯入包java.util.*
    private boolean f_sql = false; // 是否需要匯入包java.sql.*
    private boolean f_lang = false; // 是否需要匯入包java.sql.*
    private String defaultPath = "/src/main/java/";
    // 資料庫連線
    private static final String URL = "jdbc:mysql://192.168.1.xxx:3306/xxx";
    private static final String NAME = "user";
    private static final String PASS = "passwd";
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    /*
     * 建構函式
     */
    public SqlHelper() {
        // 建立連線
        Connection con;
        // 查要生成實體類的表
        String sql = "select * from " + tablename;
        PreparedStatement pStemt = null;
        try {
            try {
                Class.forName(DRIVER);
            } catch (ClassNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            con = DriverManager.getConnection(URL, NAME, PASS);
            pStemt = con.prepareStatement(sql);
            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")) {
                // f_util = true;
                // }
                if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")
                        || colTypes[i].equalsIgnoreCase("datetime") || colTypes[i].equalsIgnoreCase("time")
                        || colTypes[i].equalsIgnoreCase("date") || colTypes[i].equalsIgnoreCase("datetime2")) {
                    f_sql = true;
                }
                // if (colTypes[i].equalsIgnoreCase("int")) {
                // f_lang = true;
                // }
                colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
            }

            String content = parse(colnames, colTypes, colSizes);

            try {
                File directory = new File("");

                String path = this.getClass().getResource("").getPath();

                System.out.println(path);

                String outputPath = directory.getAbsolutePath() + this.defaultPath
                        + this.packageOutPath.replace(".", "/") + "/" + initcap(underlineToHump(tablename)) + ".java";
                System.out.println("執行完畢,生成路徑為:"+outputPath);
                FileWriter fw = new FileWriter(outputPath);
                PrintWriter pw = new PrintWriter(fw);
                pw.println(content);
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * 功能:生成實體類主體程式碼
     *
     * @param colnames
     * @param colTypes
     * @param colSizes
     * @return
     */
    private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
        StringBuffer sb = new StringBuffer();
        // 生成package包路徑
        sb.append("package " + this.packageOutPath + ";\r\n");
        // 判斷是否匯入工具包
        if (f_util) {
            sb.append("import java.util.Date;\r\n");
        }
        if (f_sql) {
            sb.append("import java.sql.*;\r\n");
        }
        if (f_lang) {
            sb.append("import java.lang.*;\r\n");
        }
        sb.append("import lombok.Data;\r\n");

        sb.append("\r\n");
        // 註釋部分
        sb.append("   /**\r\n");
        sb.append("    * @檔名稱:" + initcap(underlineToHump(this.tablename)) + ".java\r\n");
        sb.append("    * @建立時間:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\r\n");
        sb.append("    * @創  建  人:" + this.authorName + " \r\n");
        sb.append("    * @檔案描述:" + tablename + " 實體類\r\n");
        sb.append("    * @檔案版本:" + this.version + " \r\n");
        sb.append("    */ \r\n");
        sb.append("\n\r\
[email protected]
"); // 實體部分 sb.append("\npublic class " + initcap(underlineToHump(tablename)) + "{\r\n"); processAllAttrs(sb);// 屬性 // processAllMethod(sb);// get set方法 sb.append("}\r\n"); // System.out.println(sb.toString()); return sb.toString(); } /** * 功能:生成所有屬性 * * @param sb */ private void processAllAttrs(StringBuffer sb) { for (int i = 0; i < colnames.length; i++) { sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + this.underlineToHump(colnames[i]) + ";\r\n"); } } /** * 功能:生成所有方法 * * @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("\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n"); // sb.append("\t}\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"); // } // // } /** * 功能:將輸入字串的首字母改成大寫 * * @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); } /** * 功能:獲得列的資料型別 * * @param sqlType * @return */ private String sqlType2JavaType(String sqlType) { if (sqlType.equalsIgnoreCase("bit")) { return "Boolean"; } else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney") || sqlType.equalsIgnoreCase("numeric") || sqlType.equalsIgnoreCase("bigint")) { return "Long"; } else if (sqlType.equalsIgnoreCase("float")) { return "Double"; } else if (sqlType.equalsIgnoreCase("int") || sqlType.equalsIgnoreCase("int identity")) { return "Integer"; } else if (sqlType.equalsIgnoreCase("image") || sqlType.equalsIgnoreCase("varbinary(max)") || sqlType.equalsIgnoreCase("varbinary") || sqlType.equalsIgnoreCase("udt") || sqlType.equalsIgnoreCase("binary")) { return "Byte[]"; } else if (sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("nvarchar(max)") || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nvarchar(ntext)") || sqlType.equalsIgnoreCase("uniqueidentifier") || sqlType.equalsIgnoreCase("xml") || sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("varchar(max)") || sqlType.equalsIgnoreCase("text") || sqlType.equalsIgnoreCase("varchar")) { return "String"; } else if (sqlType.equalsIgnoreCase("real")) { return "Float"; } else if (sqlType.equalsIgnoreCase("smallint") || sqlType.equalsIgnoreCase("tinyint")) { return "Short"; } else if (sqlType.equalsIgnoreCase("date") || sqlType.equalsIgnoreCase("datetime") || sqlType.equalsIgnoreCase("time") || sqlType.equalsIgnoreCase("datetime2") || sqlType.equalsIgnoreCase("timestamp") ) { return "Date"; } else { System.out.println("資料型別異常,型別為:" + sqlType); } return null; } /** * 下劃線轉駝峰 * * @String para */ private String underlineToHump(String para){ StringBuilder result=new StringBuilder(); String a[]=para.split("_"); for(String s:a){ if(result.length()==0){ result.append(s.toLowerCase()); }else{ result.append(s.substring(0, 1).toUpperCase()); result.append(s.substring(1).toLowerCase()); } } return result.toString(); } /** * 出口 TODO * * @param args */ public static void main(String[] args) { new SqlHelper(); } }