• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

小程序---根据数据库反向生成java文件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

工作中写entry太繁琐,写了一个小程序反向生成。从而大大减少了工作量


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author weiwei.Wang
 * @date 2016年7月14日
 * @todo TODO 根据DB name获取数据库中的table,从而生成java文件
 * 
 */
public class CreateBean {

    private String[] colnames; // 列名数组

    private String[] colTypes; // 列名类型数组

    private int[] colSizes; // 列名大小数组

    private boolean f_util = false; // 是否需要导入包java.util.*

    private boolean f_sql = false; // 是否需要导入包java.sql.*

    private String url = "jdbc:mysql://127.0.0.1:3306/enrichmind";
    private String user = "root";
    private String pwd = "";

    /**
     * 获取数据库连接
     * 
     * @return
     */
    public Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, pwd);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 根据数据库名生成bean java文件
     * 
     * @param path
     * @throws Exception
     */
    public void createBeanMethod(String DBName, String javaFileSavePath)
            throws Exception {

        // myDB为数据库名
        List<String> tableList = getTableNameByDBname(DBName);
        for (int j = 0; j < tableList.size(); j++) {
            Connection conn = getConnection(); // 得到数据库连接
            String tableName = tableList.get(j);
            String strsql = "select * from " + tableName;
            PreparedStatement pstmt = null;
            ResultSetMetaData rsmd = null;
            try {
                pstmt = conn.prepareStatement(strsql);
                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] = 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);
                }
                String content = parse(colnames, colTypes, colSizes,
                        javaFileSavePath, tableName);

                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 {
                    pstmt.close();
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 根据数据库名获取所有table
     * 
     * @param DBname
     * @return
     */
    public List<String> getTableNameByDBname(String DBname) {
        List<String> list = new ArrayList<String>();
        try {
            Connection conn = getConnection();
            DatabaseMetaData dmd = (DatabaseMetaData) conn.getMetaData();
            ResultSet rs = dmd.getTables(null, null, "%", null);
            while (rs.next()) {
                // System.err.println("======"+ rs.getString("TABLE_NAME"));
                list.add(rs.getString("TABLE_NAME"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 解析处理(生成实体类主体代码)
     * 
     * @throws Exception
     */
    private String parse(String[] colNames, String[] colTypes, int[] colSizes,
            String path, String tableName) throws Exception {
        StringBuffer sb = new StringBuffer();

        sb.append("import lombok.Data;\r\n");
        if (f_util) {
            sb.append("\r\n");
            sb.append("import java.util.Date;\r\n");
        }
        if (f_sql) {
            sb.append("\r\n");
            sb.append("import java.sql.*;\r\n\r\n\r\n");
        }
        sb.append("@Data\r\n");
        sb.append("public class " + initcap(tableName)
                + " extends AbstractEntity" + " {\r\n");
        processAllAttrs(sb);
        // processAllMethod(sb);
        sb.append("}\r\n");

        // 将string流写入文件
        FileOperation.writeTxtFile(sb.toString(), new File(path
                + initcap(tableName) + ".java"));
        System.out.println(sb.toString());
        return sb.toString();

    }

    /**
     * 生成所有的方法
     * 
     * @param sb
     */
    @SuppressWarnings("unused")
    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");

            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");
        }
    }

    /**
     * 解析输出属性
     * 
     * @return
     */
    private void processAllAttrs(StringBuffer sb) {
        for (int i = 0; i < colnames.length; i++) {
            sb.append("\r\n");
            sb.append("\t@Column(name = \"" + colnames[i] + "\")\r\n");
            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 new String(ch);
    }

    /**
     * 将所有数据库中的字段类型转换为java中类型
     * 
     * @param sqlType
     * @return
     */
    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")) {
            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) throws Exception {
        CreateBean createBean = new CreateBean();
        String javaFileSavePath = "D:\\wer\\"; //
        String DBname = "enrichmind";
        createBean.createBeanMethod(DBname, javaFileSavePath);

    }
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap