欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

根据数据库自动生成实体类

程序员文章站 2022-06-15 13:40:07
...
package com.qianmi.kstore;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ChenDaiming
 * @since 2016/5/12 16:17.
 */
public class TablesUtil {

    private  final String RN_1 = "\r\n";
    private  final String RN_2 = RN_1 + RN_1;

    //@author
    private  final String author = "ChenDaiMing";
    //文件名
    private  final String FILENAME = "CustomerAddress";
    //文件地址
    private  final String FILEPATH="D:\\workspace\\kstore-v3-platform\\kstore-modules\\kstore-customer\\src\\main\\java\\com\\qianmi\\kstore\\manage";
    //文件包名
    private  final String PACKAGE = "com.qianmi.kstore.manage";
    //继承类名(可为空)
    private  final String EXTENDS_NAME = "";
    //实现类名(可为空)
    private  final String IMPL_NAME = "Serializable";
    //导包
    private  final String[] IMPORT_CLASS = {"lombok.Data",
                                            "java.io.Serializable",
                                            "javax.persistence.*",
                                            "java.util.Date"
    };
    //表
    private  final String table = "customer";
    //数据库
    private  final String database = "dababase";



    private  final String URL = "jdbc:mysql://172.1.2.3:3306/database?characterEncoding=UTF-8&&zeroDateTimeBehavior=convertToNull";
    private  final String NAME = "root";
    private  final String PASSWORD = "123456";
    private  final String DRIVER = "com.mysql.jdbc.Driver";
    private  final String SQL = "select COLUMN_NAME,COLUMN_TYPE,column_comment from INFORMATION_SCHEMA.Columns where table_name='"+table+"' and table_schema = '"+database+"'";
    /**
     * 执行主线程
     * @param args
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        new TablesUtil().createFile();
    }

    /**
     * 创建文件
     */
    public void createFile() {
        String dateAnnotation = "/**"+RN_1+" * @author "+author+RN_1+" * @since "+getDate()+RN_1+"*/"+RN_1;
        // 文件夹路径
        String dirPath = FILEPATH +"/";
        String fileName = dirPath+FILENAME+".java";
        File file = new File(dirPath);
        if(!file.exists()){
            if(file.mkdirs()){
                try {
                    new File(fileName).createNewFile();
                } catch (IOException e) {
                    showError(fileName);
                    e.printStackTrace();
                    return;
                }
            }
        }
        FileWriter fw = null;
        try {
            fw = new FileWriter(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("package ");
        sb.append(PACKAGE);
        sb.append(";");
        sb.append(RN_2);
        if(IMPORT_CLASS.length > 0){
            for (int i = 0; i < IMPORT_CLASS.length ; i++) {
                sb.append("import ");
                sb.append(IMPORT_CLASS[i]);
                sb.append(";");
                sb.append(RN_1);
            }
            sb.append(RN_1);
        }
        sb.append(dateAnnotation);
        sb.append("@Data"+RN_1);
        sb.append("@Entity"+RN_1);
        sb.append("@Table(name = \""+table+"\")"+RN_1);
        sb.append("public class ");
        sb.append(FILENAME);
        sb.append(" ");
        if(!EXTENDS_NAME.equals("")){
            sb.append("extends ");
            sb.append(EXTENDS_NAME);
            sb.append(" ");
        }
        if(!IMPL_NAME.equals("")){
            sb.append("implements ");
            sb.append(IMPL_NAME);
        }
        sb.append("{");
        sb.append(RN_1);
        //添加内容
        sb.append(createContent());
        sb.append(RN_2);
        sb.append("}");
        String path = sb.toString();
        try {
            if(fw!=null){
                fw.write(path);
                showInfo(fileName);
            }

        } catch (IOException e) {
            showError(fileName);
            e.printStackTrace();
        } finally {
            try {
                if(fw!=null){
                    fw.flush();
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加内容
     * @return
     */
    public String createContent(){
        List<Table> tables = queryTable();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < tables.size(); i++) {
            Table table = tables.get(i);
            sb.append(RN_2);
            sb.append("/**"+RN_1);
            sb.append(" *"+table.getParamDesc()+RN_1);
            sb.append("*/"+RN_1);
            if(i == 0){
                sb.append("@Id"+RN_1);
                sb.append("@GeneratedValue"+RN_1);
            }
            sb.append("@Column(name = \""+table.getParamName()+"\")"+RN_1);
            sb.append("private "+ getType(table.getParamype()) +" "+ getParamName(table.getParamName()));
            sb.append(";");
        }
        return sb.toString();
    }


    /**
     * 获取类型
     */
    public String getType(String type){
        if(type.contains("bigint")) {
            return "Long";
        }else if(type.contains("timestamp")){
            return "Date";
        }else{
            return "String";
        }
    }

    /**
     * 获取属性名称
     */
    public String getParamName(String param){
        if(param.contains("_")){
            String[] params = param.split("_");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < params.length; i++) {
                if(i == 0){
                    sb.append(params[i]);
                }else{
                    sb.append(params[i].substring(0, 1).toUpperCase() + params[i].substring(1));
                }
            }
            return sb.toString();
        }else{
            return param;
        }
    }


    /**
     * 添加构造函数
     * @param proName
     * @param className
     * @return
     */
    private String createConstructor(String proName,String className){
        StringBuilder sb = new StringBuilder();
        sb.append("public ");
        sb.append(FILENAME);
        sb.append("(String name){");
        sb.append(RN_1);
        sb.append("super(name);");
        sb.append(RN_1);
        sb.append("if(");
        sb.append(proName);
        sb.append("==null){");
        sb.append(RN_1);
        sb.append(proName);
        sb.append(" = new ");
        sb.append(className);
        sb.append("();");
        sb.append(RN_1);
        sb.append("}}");
        sb.append(RN_2);
        //添加无参构造
        sb.append("public ");
        sb.append(FILENAME);
        sb.append("(){");
        sb.append(RN_1);
        sb.append("super();");
        sb.append(RN_2);
        sb.append("}");
        String constructor = sb.toString();
        return constructor;
    }



    /**
     * 查询数据库表数据
     */
    private List<Table> queryTable(){
        List<Table> tables = new ArrayList<Table>();
        try {
            Class.forName(DRIVER).newInstance();

            Connection con = DriverManager.getConnection(URL,NAME,PASSWORD);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(SQL);
            while (rs.next()){
                tables.add(new Table(rs.getString(1),rs.getString(2),rs.getString(3)));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tables;
    }


    /**
     * 显示创建信息
     */
    private  void showInfo(String info) {
        System.out.println("创建文件:" + info + "成功!");
    }

    /**
     * 显示错误信息
     */
    private  void showError(String info){
        System.out.println("创建文件:"+info+"失败!");
    }

    /**
     * 获取系统时间
     */
    public  String getDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date());
    }

    public class Table{
        public String paramName;
        public String paramype;
        public String paramDesc;

        public Table(String paramName, String paramype, String paramDesc) {
            this.paramName = paramName;
            this.paramype = paramype;
            this.paramDesc = paramDesc;
        }

        public String getParamName() {
            return paramName;
        }

        public String getParamype() {
            return paramype;
        }

        public String getParamDesc() {
            return paramDesc;
        }

        public void setParamName(String paramName) {
            this.paramName = paramName;
        }

        public void setParamype(String paramype) {
            this.paramype = paramype;
        }

        public void setParamDesc(String paramDesc) {
            this.paramDesc = paramDesc;
        }
    }
}