Java代码实体类生成SQL语句(Java实体类转数据库)
蜂信物联FastBee平台https://gitee.com/beecue/fastbee
阿里资料开源项目https://gitee.com/vip204888
百度低代码前端框架https://gitee.com/baidu/amis
OpenHarmony开源项目https://gitcode.com/openharmony
仓颉编程语言开放项目https://gitcode.com/Cangjie
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(”;\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 = f.getName();
System.out.println(column + ", " + f.getType().getSimpleName());
param = f.getType();
sb.append(column); // 一般第一个是主键
面试准备+复习分享:
为了应付面试也刷了很多的面试题与资料,现在就分享给有需要的读者朋友,资料我只截取出来一部分哦

etSimpleName());
param = f.getType();
sb.append(column); // 一般第一个是主键
面试准备+复习分享:
为了应付面试也刷了很多的面试题与资料,现在就分享给有需要的读者朋友,资料我只截取出来一部分哦
[外链图片转存中…(img-uUDimaay-1725158446302)]
更多推荐



所有评论(0)