分享一段通过已有的实体类,生成建表语句(mysql)
直接上代码
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CreateTableSQLUtil {
public static void main(String[] args){
createTableSQL(IntelligentCalculation.class, "intel_intelligent_calculation", Arrays.asList("serialVersionUID"));
}
public static void createTableSQL(Class<?> clazz){
createTableSQL(clazz,null);
}
public static void createTableSQL(Class<?> clazz,String tableName){
createTableSQL(clazz,tableName, new ArrayList<>());
}
/**
* 建表sql
* @param clazz
* @param tableName
* @param excludeFields
*/
public static void createTableSQL(Class<?> clazz,String tableName, List<String> excludeFields){
Field[] fields = null;
BufferedWriter out = null;
try {
fields =getAllFields(clazz);
Class<?> annotationType = null;
String param = null;
String column = null;
StringBuilder sb = null;
sb = new StringBuilder(50);
if(StrUtil.isBlank(tableName)){
tableName = clazz.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");
boolean firstId = false;
boolean firstLine = true;
File file = null;
for(Field f:fields){
if(excludeFields.contains(f.getName())) {
continue;
}
if(!firstLine) {
sb.append(",\n ");
}
firstLine = false;
column = "`" + xX2x_x(f.getName()) + "`";
if(f.getName().equalsIgnoreCase("id")) {
firstId = true;
}
sb.append(column).append(" ");
param = f.getType().getName();
if(param.contains("Integer")){
sb.append(" int(11) ");
} else if(param.contains("Long")){
sb.append(" bigint(18) ");
} else if(param.contains("Double")){
sb.append(" double(16,4) ");
} else if(param.contains("BigDecimal")){
sb.append(" decimal(20,8) ");
}else if(param.contains("String")){
sb.append(" VARCHAR(255) ");
} else if(param.contains("LocalDateTime") || param.contains("Date")){
sb.append(" datetime ");
} else if(param.contains("Boolean")){
sb.append(" bit(1) ");
}else {
sb.append(" json ");
}
if(firstId){//类型转换
sb.append(" NOT NULL AUTO_INCREMENT ");
sb.append(" PRIMARY KEY ");
firstId = false;
} else {
sb.append(" DEFAULT NULL ");
}
}
sb.append("\n ");
String sql = sb.toString();
sql = sb.substring(0, sql.length()-1)+" )ENGINE =INNODB DEFAULT CHARSET= utf8;\r\n";
file = new File("sql/createTable/" + tableName + ".sql");
if (!file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
}
}
if (!file.exists()) {
file.createNewFile();
}
System.out.println("文件路径:"+file.getAbsolutePath());
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
out.write(sql) ;
out.flush();
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
if(null != out) {
try {
out.close() ;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @Description 将驼峰转为下划线
* @param str
* @return java.lang.String
*/
public static String xX2x_x(String str) {
Pattern compile = Pattern.compile("[A-Z]");
Matcher matcher = compile.matcher(str);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* @Description 将下划线转为驼峰
* @param str
* @return java.lang.String
*/
public static String x_x2xX(String str) {
str = str.toLowerCase();
Pattern compile = Pattern.compile("_[a-z]");
Matcher matcher = compile.matcher(str);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, matcher.group(0).toUpperCase().replace("_",""));
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 获取实体所有字段包括父类
* @param clazz
* @return
*/
public static Field[] getAllFields(Class<?> clazz){
List<Field> fieldList = new ArrayList<>();
while (clazz != null){
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
}
- 会在项目的根目录创建sql文件夹,需要修改路径的同学自己注意
- 主键需要是字符“id”,自动默认为自增类型
- 使用到了hutool工具类,不想要的可以自行替换
- 生成的sql包含删除已存在相同表名的语句,请小心执行