通过实体类生成 mysql 的建表语句

本文介绍了一个使用Java反射和注解处理技术,将实体类转换为MySQL数据库建表语句的方法。该方法能够自动生成DROP TABLE和CREATE TABLE SQL语句,并将结果保存至指定文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.xml.bind.annotation.XmlElement;

// 通过实体类生成 mysql 的建表语句
public class GenerateSqlFromEntity{
	// main
	public static void main(String[] a){
		Class klass = com.entity.User.class;
		String outputPath = "输出建表语句/建表语句.txt";   // c:/

		generateTableSql(klass, outputPath, null);

		System.out.println("操作结束");
	}

	// writeFile with BufferedWriter
	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 = null;
		String column = null;

		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);  // 一般第一个是主键

			if(param instanceof Integer){
				sb.append(" INTEGER ");
			}else{
				// 注意:根据需要,自行修改 varchar 的长度。这里设定为长度等于 50
				int length = 50;
				sb.append(" VARCHAR(" + length + ")");
			}

			if(firstId == true){
				sb.append(" PRIMARY KEY ");
				firstId = false;
			}

			// 获取字段中包含 fieldMeta 的注解

			// 获取属性的所有注释
			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);
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值