根据javabean转换为mysql建表语句
时间:2021-07-01 10:21:17
帮助过:84人阅读
com.util;
import java.io.IOException;
import java.lang.reflect.Field;
/**
* Created by Jeff on 2018/12/5.
*/
public class CreateTableUtil {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args)
throws IOException {
createTable(com.entity.SharingFile.class,
null);
}
public static void createTable(Class obj,String tableName)
throws IOException{
Field[] fields =
null;
fields =
obj.getDeclaredFields();
String param =
null;
String column =
null;
StringBuilder sb =
null;
sb =
new StringBuilder(50
);
if(tableName==
null||tableName.equals(""
)){
//未传表明则默认用类名
tableName =
obj.getName();
tableName = tableName.substring(tableName.lastIndexOf(".")+1
);
}
sb.append("drop table if exists ").append(tableName).append(";\r\n"
);
sb.append("create table ").append(tableName).append(" ( \r\n"
);
boolean firstId =
true;
for(Field f : fields){
column =
f.getName();
for(
int i = 0; i < column.length(); i++
)
if(Character.isUpperCase(column.charAt(i)))
column = column.substring(0, i) + ‘_‘ + column.substring(i, i+1).toLowerCase() + column.substring(i+1
, column.length());
sb.append(column).append(" "
);
param =
f.getType().getTypeName();
if(param.equals("java.lang.Integer"
)){
sb.append("INTEGER"
);
}else{
sb.append("VARCHAR(20)");
//根据需要自行修改
}
if(firstId){
//类型转换
sb.append(" PRIMARY KEY AUTO_INCREMENT"
);
firstId =
false;
}
sb.append(",\n"
);
}
String sql =
null;
sql =
sb.toString();
sql = sb.substring(0, sql.length()-2)+"\n)ENGINE = INNODB DEFAULT CHARSET= utf8 AUTO_INCREMENT=1;\r\n"
;
System.out.println(sql);
}
}
根据javabean转换为mysql建表语句
标签:cep void pre end substr \n arch table append