有的时候把数据库删了,如果照着实体类重新创建数据库的话比较麻烦,可以使用这个工具,把代码复制到项目里面设置一下即可把Java代码中的实体类转换为SQL语句输出为一个文件,打开执行命令即可。
下载:download.csdn.net/download/weixin_44893902/20367422
代码如下:package Main;
import javax.xml.bind.annotation.XmlElement;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class GenerateSqlFromEntityUtil {
public static void main(String[] a) {
// 实体类的位置
Class klass = cn.ac.azure.model.User.class;
// 生成的sql语句的位置
String outputPath = "D:/outSql/User.txt";
generateTableSql(klass, outputPath, null);
System.out.println("生成结束");
}
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;
String column;
StringBuilder sb = new StringBuilder();
sb.append("drop table if exists ").append(tableName).append(";rn");
sb.append("rn");
sb.append("create table ").append(tableName).append("(rn");
System.out.println(tableName);
boolean firstId = true;
for (int i = 0; i }
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2751/viewspace-2797439/ ,如需转载,请注明出处,否则将追究法律责任。