Java通过表名生成实体类代码

package com.firefly.performance.core.utils;

import lombok.extern.slf4j.Slf4j;

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;

/**
 * @Description:通过表名生成实体类代码
 * @Author: zhangPing
 * @Date: 2022/4/14/0014 15:05
 **/
@Slf4j
public class GenEntityMysql {

    /**
     * 指定实体生成所在包的路径
     */
    private String packageOutPath = "com.firefly.performance.core.entity";
    /**
     * 作者名字
     */
    private String authorName = "zhangPing";
    /**
     * 列名数组
     */
    private String[] colNames;
    /**
     * 列名类型数组
     */
    private String[] colTypes;
    /**
     * 列名大小数组
     */
    private int[] colSizes;
    /**
     * 是否需要导入包java.util.*
     */
    private boolean f_util = false;
    /**
     * 是否需要导入包java.sql.*
     */
    private boolean f_sql = false;
    /**
     * 表名
     */
    private String TABLE_NAME = "t_personal_performance";
    /**
     * 数据库连接
     */
    private static final String URL ="jdbc:mysql://10.164.15.36:3306/firefly_performance";
    private static final String NAME = "fengniao";
    private static final String PASS = "Fn20200721$";
    private static final String DRIVER ="com.mysql.jdbc.Driver";

    /**
     * 构造函数
     */
    public GenEntityMysql(){
        //创建连接
        Connection con = null;
        FileWriter fw = null;
        //查要生成实体类的表
        String sql = "select * from " + TABLE_NAME;

        TABLE_NAME = initCap(TABLE_NAME);
        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] = initCap(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);

            try {
                File directory = new File("");
                String path=this.getClass().getResource("").getPath();
                String outputPath = directory.getAbsolutePath()+ "/firefly-performance/firefly-performance-core/src/main/java/"+this.packageOutPath.replace(".", "/")+"/"+initcap(TABLE_NAME) + ".java";
                log.info("生成实体类路径:{}",outputPath);
                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{
            try {
                if(null != fw){
                    fw.close();
                }
                pStemt.close();
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 功能:生成实体类主体代码
     * @param colNames
     * @param colTypes
     * @param colSizes
     * @return
     */
    private String parse(String[] colNames, String[] colTypes, int[] colSizes) {
        StringBuffer sb = new StringBuffer();

        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");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sb.append("\r\n");
        //注释部分
        sb.append("/**\r\n");
        sb.append("* "+TABLE_NAME+" 实体类\r\n");
        sb.append("* "+simpleDateFormat.format(new Date())+" "+this.authorName+"\r\n");
        sb.append("*/ \r\n");
        //实体部分
        sb.append("\r\npublic class " + initcap(TABLE_NAME) + "{\r\n");
        //属性
        processAllAttrs(sb);
        //get set方法
        //processAllMethod(sb);
        sb.append("}\r\n");
        return sb.toString();
    }

    /**
     * 功能:生成所有属性
     * @param sb
     */
    private void processAllAttrs(StringBuffer sb) {

        for (int i = 0; i < colNames.length; i++) {
            sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + 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 str1
     * @return
     */
    private String initCap(String str1) {

        String[] str1s = str1.split("_");

        String feild = str1s[0];
        for(int i=1;i<str1s.length;i++){
            char[] ch = str1s[i].toCharArray();
            if(ch[0] >= 'a' && ch[0] <= 'z'){
                ch[0] = (char)(ch[0] - 32);
            }
            feild+=new String(ch);
        }


        return feild;
    }

    /**
     * 功能:获得列的数据类型
     * @param sqlType
     * @return
     */
    private String sqlType2JavaType(String sqlType) {

        if(sqlType.equalsIgnoreCase("bit")){
            return "Boolean";
        }else if(sqlType.equalsIgnoreCase("tinyint")){
            return "Byte";
        }else if(sqlType.equalsIgnoreCase("smallint")){
            return "Short";
        }else if(sqlType.equalsIgnoreCase("int")){
            return "Integer";
        }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") || sqlType.equalsIgnoreCase("money")
                || sqlType.equalsIgnoreCase("smallmoney")){
            return "BigDecimal";
        }else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
                || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
                || sqlType.equalsIgnoreCase("text")){
            return "String";
        }else if(sqlType.equalsIgnoreCase("datetime")){
            return "Date";
        }else if(sqlType.equalsIgnoreCase("image")){
            return "Blod";
        }

        return null;
    }

    /**
     * 出口
     * TODO
     * @param args
     */
   public static void main(String[] args) {
        new GenEntityMysql();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值