1. 程式人生 > >通過實體類生成 sql 建表語句

通過實體類生成 sql 建表語句



import java.io.BufferedWriter;
import java.io.File;
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;


public class CreateTable {


/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {
createTable(User.class, null);
//createTable(Book.class, null);
}
public static void createTable(Class obj,String tableName) throws IOException{


Field[] fields = null;
fields = obj.getDeclaredFields();
Class annotationType = null;
Object param = null;
String column = null;
XmlElement xmlElement = null;
StringBuilder sb = null;
sb = new StringBuilder(50);
if(tableName==null||tableName.equals("")){
//未傳表明預設用類名
tableName = obj.getName();
tableName = tableName.substring(tableName.lastIndexOf(".")+1);
}
sb.append("\r\ndrop table if exists  ").append(tableName).append(";\r\n");
sb.append("create table ").append(tableName).append(" ( \r\n");
System.out.println(tableName);
boolean firstId = true;
File file = null;
for(Field f:fields){
column = f.getName();
sb.append(column).append(" ");
System.out.println(column+","+f.getType());
param = f.getType();
sb.append(column);//一般第一個是主鍵
if(param instanceof Integer){
sb.append(" INTEGER ");
}else{
sb.append(" VARCHAR(30) ");//根據需要自行修改
}
if(firstId){//型別轉換
sb.append(" PRIMARY KEY ");
firstId = false;
}
  //獲取欄位中包含fieldMeta的註解  
 //2、獲取屬性上的所有註釋
     Annotation[] allAnnotations = f.getAnnotations();
     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("'");
     }
     sb.append(",\n ");
}
String sql = null;
sql = sb.toString();
sql = sb.substring(0, sql.length()-1)+" )ENGINE =INNODB DEFAULT  CHARSET= utf8;\r\n";
file = new File("WebContent/createTable/建表.txt");
if (!file.getParentFile().exists()) {  
            if (!file.getParentFile().mkdirs()) {  
            }  
}  
if (!file.exists()) {
file.createNewFile();
}
System.out.println("檔案路徑:"+file.getAbsolutePath());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
out.write(sql) ;
out.flush();
out.close() ;

}

}