oracle数据库,逆向生成实体类,代码示例

/**
     * 向实体类中按行生成代码
     * @param str
     * @param out
     * @throws Exception
     */
    public static void createBean(String str,BufferedWriter out) throws Exception {
        if(str.contains("\n")) {
            String[] split = str.split("\n");
            for(int i=0;i='A' && charArray[i]<='Z') {
                sum++;
            }
        }
        return sum;
    }
    /**
     * 将含有大写字母的入参,大写字母转为小写,并在前面加下划线
     * 入参示例:userName
     * @param str
     * @return
     */
    public static String to_lowerCase(String str) {
        StringBuilder sb = new StringBuilder();
        char[] charArray = str.toCharArray();
        for(int i=0;i='A' && charArray[i]<='Z') {
                // 大写转为小写,并且前面加下划线
                String lowerCase = String.valueOf(charArray[i]).toLowerCase();
                sb.append("_").append(lowerCase);
            }else {
                sb.append(charArray[i]);
            }
        }
        return sb.toString();
    }
    /**
     * 获取指定表名的javabean数据
     * 入参示例:AE01_DICTIONARY_DST
     * @param tableName
     * @throws Exception 
     */
    public static void getJavaBean(String tableName) throws Exception {
        /**获取基础行业数据:前置机数据库地址: */
        String url="jdbc:oracle:thin:@*.*.*.*:1521:B";
        String user="";
        String password="";
        Connection c = DriverManager.getConnection(url,user,password);
        Statement createStatement = c.createStatement();
        /** 查询指定表的列名称、列类型、列长度、列注释   */
//      String tableName = "AE01_DICTIONARY_DST";
        String sql2 = "SELECT T1.TABLE_NAME,\r\n" + 
                "T1.COLUMN_NAME,\r\n" + 
                "T1.DATA_TYPE || '(' || T1.DATA_LENGTH || ')',\r\n" + 
                "T1.DATA_PRECISION,\r\n" + 
                "T1.DATA_SCALE,\r\n" + 
                "T2.COMMENTS\r\n" + 
                "FROM USER_TAB_COLS T1, USER_COL_COMMENTS T2\r\n" + 
                "WHERE T1.TABLE_NAME = T2.TABLE_NAME\r\n" + 
                "AND T1.COLUMN_NAME = T2.COLUMN_NAME\r\n" + 
//              "AND T1.TABLE_NAME =upper('ae01_dictionary_dst')";
                "AND T1.TABLE_NAME = '"+tableName+"'";
        ResultSet rs = createStatement.executeQuery(sql2);
        /** 打印类的包名、引入的类、类的命名等等  */
        StringBuilder headsb = new StringBuilder();
        headsb.append("package cn.com.taiji.api.jtwget.entity;\n");
        headsb.append("import javax.persistence.Entity;\n");
        headsb.append("import javax.persistence.Table;\n");
        headsb.append("import java.time.LocalDateTime;\n");
        headsb.append("import javax.persistence.Column;\n");
        headsb.append("@Entity\n");
        String lowerCase = tableName.toLowerCase();
        headsb.append("@Table(name = \""+lowerCase+"\")"+"\n");
        String l2 = Util.toLowerCase(tableName);
        String name2 = l2.substring(1, l2.length());
        String name = l2.substring(0,1).toUpperCase().concat(name2);
        headsb.append("public class "+name+" {\n");
        /**写入相应的文件*/
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream("C:\\Users\\tom\\Desktop\\get\\"+name+".java"),"utf-8"));
        System.out.println(headsb);
        createBean(headsb.toString(), out);
        List vars = new ArrayList<>();
        while(rs.next()) { // 查询所有表名时,返回的是一个集合
            StringBuilder sb = new StringBuilder();
            sb.append("private ");
            String type = rs.getString(3); // 类型
            String dataPrecision = rs.getString(4); // 精度
            String dataScale = rs.getString(5); // (小数)数值范围
            /** 类型转换 */
            String javaType = "";
            if(type.contains("VARCHAR2")) {
                javaType = "String";
                sb.append(javaType+" ");
            }
            if(type.contains("NUMBER") && (null == dataScale || dataScale.equals("0")) ) {
                javaType = "Integer";
                sb.append(javaType+" ");
            }
            if(type.contains("NUMBER") && null != dataScale && !dataScale.equals("0")) {
                javaType = "Double";
                sb.append(javaType+" ");
            }
            if(type.contains("DATE")) {
                javaType = "LocalDateTime";
                sb.append(javaType+" ");
            }
            if(type.contains("CHAR(")) {
                javaType = "String";
                sb.append(javaType+" ");
            }
            if(type.contains("TIMESTAMP")) {
                javaType = "LocalDateTime";
                sb.append(javaType+" ");
            }
            if(type.contains("BLOB")) {
                javaType = "Blob"; // java.sql.Blob
                sb.append(javaType+" ");
            }
            // 字段,以及后面加特定符号
            String variable = rs.getString(2);
            /** 处理字段,小写、驼峰规则    */
            variable = Util.toLowerCase(variable);
            /** 收集字段名称 */
            vars.add(variable+","+javaType);
            sb.append(variable).append("; //  ");
            // 整理非number类型的展示方式
            if(!type.contains("NUMBER")) {
                sb.append(type).append("  ");
            }
            // 整理number类型的展示方式
            if(type.contains("NUMBER")) {
                sb.append("NUMBER("+dataPrecision+","+dataScale+")  ");
            }
            sb.append(rs.getString(6)); // 注释
            
            /** 打印一行完整的字段 */
            System.out.println(sb.toString());
            createBean(sb.toString(), out);
        }
        /** 处理字段名称集合,生成get、set方法    */
        for(String s:vars) {
            // System.out.println(s); // itemCode,String
            String[] split = s.split(",");
            StringBuilder sb = new StringBuilder();
            char v1 = split[0].charAt(0);
            String v = split[0].replace(v1, String.valueOf(v1).toUpperCase().toCharArray()[0]);
            /** 首字母大写 */
            String v2 = split[0].substring(1, split[0].length());
            v = split[0].substring(0,1).toUpperCase().concat(v2);
            
            int countUpperCase = Util.countUpperCase(split[0]);
            if(countUpperCase > 0) {
                String to_lowerCase = Util.to_lowerCase(split[0]);
                sb.append("@Column(name=\""+to_lowerCase+"\")\n");
            }
            sb.append("public "+split[1]+" get"+v+"() {\n");
            sb.append(" return "+split[0]+";\n");
            sb.append("}\n");
            sb.append("public void "+"set"+v+"("+split[1]+" "+split[0]+") {\n");
            sb.append(" this."+split[0]+" = "+split[0]+";\n");
            sb.append("}");
            System.out.println(sb.toString()); // 打印,一个字段的get、set方法
            createBean(sb.toString(), out);
        }
        System.out.println("}"); // 打印,类的最后一个花括号
        createBean("}", out);
        //清楚缓存
        out.flush();
        //关闭流
        out.close();
    }
    /**
     * 获取oracle数据库中的所有表名
     * @return
     * @throws SQLException
     */
    public static List getTableNames() throws SQLException {
        /**获取基础行业数据:前置机数据库地址: */
        String url="jdbc:oracle:thin:@*.*.*.*:1521:B";
        String user="";
        String password="";
        Connection c = DriverManager.getConnection(url,user,password);
        Statement createStatement = c.createStatement();
        String sql1 = "select * from user_tables";
        ResultSet rs = createStatement.executeQuery(sql1);
        int sum = 0;
        List tableNames = new ArrayList<>();
        while(rs.next()) { // 查询所有表名时,返回的是一个集合
            String s = rs.getString(1);
            if(s.startsWith("A")) {
                sum++;
                System.out.println(s); // 表名
                tableNames.add(s);
            }
        }
        System.out.println(sum);
        return tableNames;
    }
    public static void main(String[] args) throws Exception {
        List tableNames = getTableNames();
        int sum = 1;
        for(String n:tableNames) {
            getJavaBean(n);
            System.out.println();
            System.out.println("上面是第    "+sum+++"  张表,=====================================================================================");
            System.out.println();
            // return;
        }
    }

你可能感兴趣的:(oracle数据库,逆向生成实体类,代码示例)