Java 中 通過實體類生成SQL


通過實體類生成SQL

代碼編寫

package com.huadi.java2.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

//import org.hibernate.hql.internal.ast.SqlGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Task {
//    private static final Logger logger = LoggerFactory.getLogger(SqlGenerator.class);

    /**
     * 通過實體類生成建表SQL語句實現方法
     * @param args
     */
    public static void main(String[] args) {
        //實體類所在的package在磁盤上的絕對路徑
        String packageName = "D:/Demo02/FireMaterialIdent/src/main/java/com/huadi/firematerialident/po";

        //生成sql的文件夾
        String filePath = "D:/Demo02/";
        //項目中實體類的路徑
        String prefix = "com.huadi.firematerialident.po.";
        String className = "";

        StringBuffer sqls = new StringBuffer();
        //獲取包下的所有類名稱
        List<String> list = getAllClasses(packageName);
        for (String str : list) {
            className = prefix + str.substring(0, str.lastIndexOf("."));
            String sql = generateSql(className, filePath);
            sqls.append(sql);
        }
        System.out.println(sqls.toString());
        StringToSql(sqls.toString(), filePath + "report.sql");

    }
    /**
     * 根據實體類生成建表語句
     * @author
     * @date
     * @param className 全類名
     * @param filePath 磁盤路徑  如 : d:/workspace/
     */
    public static String generateSql(String className,String filePath){
        try {
            Class<?> clz = Class.forName(className);
            className = clz.getSimpleName();
            Field[] fields = clz.getDeclaredFields();
            StringBuffer column = new StringBuffer();
            String varchar = " varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,";
            for (Field f : fields) {
                column.append(" \n `"+f.getName()+"`").append(varchar);
            }
            StringBuffer sql = new StringBuffer();
            sql.append("\n DROP TABLE IF EXISTS `"+className+"`; ")
                    .append(" \n CREATE TABLE `"+className+"`  (")
                    .append(" \n `id` int(11) NOT NULL AUTO_INCREMENT,")
                    .append(" \n "+column)
                    .append(" \n PRIMARY KEY (`id`) USING BTREE,")
                    .append("\n INDEX `id`(`id`) USING BTREE")
                    .append(" \n ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;");
            return sql.toString();
        } catch (ClassNotFoundException e) {
//            logger.debug("該類未找到!");
            return null;
        }

    }

    /**
     * 獲取包下的所有類名稱,獲取的結果類似於 XXX.java
     * @author
     * @date
     * @param packageName
     * @return
     */
    public static List<String> getAllClasses(String packageName){
        List<String> classList = new ArrayList<String>();
        String className="";
        File f = new File(packageName);
        if(f.exists() && f.isDirectory()){
            File[] files = f.listFiles();
            for (File file : files) {
                className = file.getName();
                classList.add(className);
            }
            return classList;
        }else{
//            logger.debug("包路徑未找到!");
            return null;
        }
    }
    /**
     * 將string 寫入sql文件
     * @author
     * @date
     * @param str
     * @param path
     */
    public static void StringToSql(String str,String path){
        byte[] sourceByte = str.getBytes();
        if(null != sourceByte){
            try {
                File file = new File(path);     //文件路徑(路徑+文件名)
                if (!file.exists()) {   //文件不存在則創建文件,先創建目錄
                    File dir = new File(file.getParent());
                    dir.mkdirs();
                    file.createNewFile();
                }
                FileOutputStream outStream = new FileOutputStream(file);    //文件輸出流用於將數據寫入文件
                outStream.write(sourceByte);
                outStream.flush();
                outStream.close();  //關閉文件輸出流
                System.out.println("生成成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

運行結果

生成的代碼如下(控制台):

 DROP TABLE IF EXISTS `Admin`;  
 CREATE TABLE `Admin`  ( 
 `id` int(11) NOT NULL AUTO_INCREMENT, 
  
 `AdminID` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `AdminCount` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `AdminPassword` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `AdminName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `AdminSex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `AdminBirth` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `AdminPhone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `LogicalAddDel` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `LastModification` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 PRIMARY KEY (`id`) USING BTREE,
 INDEX `id`(`id`) USING BTREE 
 ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;
......
 DROP TABLE IF EXISTS `Reviewer`;  
 CREATE TABLE `Reviewer`  ( 
 `id` int(11) NOT NULL AUTO_INCREMENT, 
  
 `RevID` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `RevCount` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `RevPassword` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `RevName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `RevSex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `RevBirth` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `RevPhone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `LogicalAddDel` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 `LastModification` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 
 PRIMARY KEY (`id`) USING BTREE,
 INDEX `id`(`id`) USING BTREE 
 ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;

生成成功

Process finished with exit code 0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM