<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>25.1-jre</version>
</dependency>
package jar;
import com.google.common.base.CaseFormat;
import javax.xml.bind.annotation.XmlElement;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class GenerateSqlFromEntityUtil {
public static void main(String[] a) throws IOException, ClassNotFoundException {
List<Class<?>> classList = GenerateSqlFromEntityUtil.getClasssFromPackage("entity");
for (Class<?> aClass : classList) {
String outputPath = "F:/outSql/"+aClass.getName()+".txt";
generateTableSql(aClass, outputPath, null);
System.out.println("生成结束");
}
}
public static List<Class<?>> getClasssFromPackage(String packageName) {
List<Class<?>> clazzs = new ArrayList<>();
boolean recursive = true;
String packageDirName = packageName.replace('.', '/');
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
while (dirs.hasMoreElements()) {
URL url = dirs.nextElement();
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
findClassInPackageByFile(packageName, filePath, recursive, clazzs);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return clazzs;
}
public static void findClassInPackageByFile(String packageName, String filePath, final boolean recursive,
List<Class<?>> clazzs) {
File dir = new File(filePath);
if (!dir.exists() || !dir.isDirectory()) {
return;
}
File[] dirFiles = dir.listFiles(new FileFilter() {
public boolean accept(File file) {
boolean acceptDir = recursive && file.isDirectory();
boolean acceptClass = file.getName().endsWith("class");
return acceptDir || acceptClass;
}
});
for (File file : dirFiles) {
if (file.isDirectory()) {
findClassInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, clazzs);
} else {
String className = file.getName().substring(0, file.getName().length() - 6);
try {
clazzs.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + "." + className));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
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) {
if (tableName == null || tableName.equals("")) {
tableName = obj.getName();
tableName = tableName.substring(tableName.lastIndexOf(".") + 1);
}
tableName = tableName.toUpperCase();
Field[] fields = obj.getDeclaredFields();
Object param;
String column;
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 = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, f.getName());
System.out.println(column + ", " + f.getType().getSimpleName());
param = f.getType();
sb.append(column);
if (param instanceof Integer) {
sb.append(" INTEGER ");
} else {
int length = 50;
sb.append(" VARCHAR(" + length + ")");
}
if (firstId == true) {
sb.append(" PRIMARY KEY ");
firstId = false;
}
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);
}
}