通過實體類生成 mysql 的建表語句

guile發表於2019-03-05
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.xml.bind.annotation.XmlElement;

// 通過實體類生成 mysql 的建表語句
public class GenerateSqlFromEntity{
	// main
	public static void main(String[] a){
		Class klass = com.entity.User.class;
		String outputPath = "輸出建表語句/建表語句.txt";   // c:/

		generateTableSql(klass, outputPath, null);

		System.out.println("操作結束");
	}

	// writeFile with BufferedWriter
	public static void writeFile(String content, String outputPath){
		File file = new File(outputPath);
		System.out.println("檔案路徑: " + file.getAbsolutePath());

		// 輸出檔案的路徑
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}

		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		BufferedWriter out = null;

		try{
			// 如果檔案存在,就刪除
			if(file.exists()){
				file.delete();
			}

			file.createNewFile();

			fos = new FileOutputStream(file, true);
			osw = new OutputStreamWriter(fos);
			out = new BufferedWriter(osw);

			out.write(content);

			// 清空緩衝流,把緩衝流裡的文字資料寫入到目標檔案裡
			out.flush();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				fos.close();
			}catch(IOException e){
				e.printStackTrace();
			}

			try{
				osw.close();
			}catch(IOException e){
				e.printStackTrace();
			}

			try{
				out.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}

	public static void generateTableSql(Class obj,
			String outputPath, String tableName){
		// tableName 如果是 null,就用類名做表名
		if(tableName == null || tableName.equals("")){
			tableName = obj.getName();
			tableName = tableName.substring(tableName.lastIndexOf(".") + 1);
		}

		// 表名用大寫字母
		tableName = tableName.toUpperCase();

		Field[] fields = obj.getDeclaredFields();

		Object param = null;
		String column = null;

		StringBuilder sb = new StringBuilder();

		sb.append("drop table if exists ").append(tableName).append(";\r\n");

		sb.append("\r\n");

		sb.append("create table ").append(tableName).append("(\r\n");

		System.out.println(tableName);

		boolean firstId = true;

		for(int i = 0; i < fields.length; i++){
			Field f = fields[i];

			column = f.getName();

			System.out.println(column + ", " + f.getType().getSimpleName());

			param = f.getType();
			sb.append(column);  // 一般第一個是主鍵

			if(param instanceof Integer){
				sb.append(" INTEGER ");
			}else{
				// 注意:根據需要,自行修改 varchar 的長度。這裡設定為長度等於 50
				int length = 50;
				sb.append(" VARCHAR(" + length + ")");
			}

			if(firstId == true){
				sb.append(" PRIMARY KEY ");
				firstId = false;
			}

			// 獲取欄位中包含 fieldMeta 的註解

			// 獲取屬性的所有註釋
			Annotation[] allAnnotations = f.getAnnotations();

			XmlElement xmlElement = null;
			Class annotationType = null;

			for(Annotation an : allAnnotations){
				sb.append(" COMMIT '");
				xmlElement =(XmlElement) an;
				annotationType = an.annotationType();
				param =((XmlElement) an).name();
				System.out.println("屬性 " + f.getName()
						+ " ----- 的註釋型別有: " + param);
				sb.append(param).append("'");
			}

			if(i != fields.length - 1){  // 最後一個屬性後面不加逗號
				sb.append(", ");
			}

			sb.append("\n");
		}

		String sql = sb.toString();

		sql = sb.substring(0, sql.length() - 1)
				+ "\n) " + "ENGINE = INNODB DEFAULT  CHARSET = utf8;";

		writeFile(sql, outputPath);
	}

}

 

相關文章