简易orm逆向工程实现

package org.com.jdbc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import java.util.Set;

public class JdbcDemo {

	public static void main(String[] args) throws Exception {
		// 注册驱动
		Class.forName("com.mysql.jdbc.Driver");
		// 创建连接
		Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "root", "root");
		// 获得数据库的原信息
		DatabaseMetaData metaData = connection.getMetaData();
		ResultSet tables = metaData.getTables("world", null, null, null);
		String pathName = "org.com.pojo";
		String createPackage = Utils.createPackage(pathName);

		while (tables.next()) {
			// String string1 = tables.getString(1);//数据库名
			// String string2 = tables.getString(2);//未知
			String table = tables.getString(3);// 表名
			ResultSet columns = metaData.getColumns("world", "world", table, null);
			// 构造一个字符串对象
			StringBuilder contentBuild = new StringBuilder();
			// 创建容器存放成员变量信息
			Map<String, String> filedMaps = new HashMap<>();
			Map<String, String> filedMappingAnnotation = new HashMap<>();
			while (columns.next()) {
				String columnName = columns.getString("COLUMN_NAME");// 字段名
				String typeName = columns.getString("TYPE_NAME");// 数据类型
				String annotation = columns.getString("REMARKS");// 注释
				filedMaps.put(columnName, typeName);
				filedMappingAnnotation.put(columnName, annotation);
			}

			contentBuild.append("package " + pathName + ";\n\n");

			Set<Entry<String, String>> entrySet = filedMaps.entrySet();
			for (Entry<String, String> entry : entrySet) {
				String importPackage = Utils.IMPORT_PACKAGE.get(entry.getValue());
				if (importPackage != null) {
					contentBuild.append(importPackage + "\n");
				}
			}

			contentBuild.append("public class " + Utils.generateClassName(table) + "{\n");

			for (Entry<String, String> entry : entrySet) {
				contentBuild.append("\t//" + filedMappingAnnotation.get(entry.getKey()) + "\n");
				contentBuild.append("\t" + "private " + Utils.SQLTYPE_TO_JAVATYPE.get(entry.getValue()) + " "
						+ Utils.generateFiledName(entry.getKey()) + ";\n\n");
			}
			
			/**
			 * set/get方法
			 */
			for (Entry<String, String> entry : entrySet) {
				contentBuild.append("\t" + "public void " + " " + "set" + Utils.generateClassName(entry.getKey()) + "("
						+ Utils.SQLTYPE_TO_JAVATYPE.get(entry.getValue()) + " "
						+ Utils.generateFiledName(entry.getKey()) + ") {" + "\n\t\t" + "this."
						+ Utils.generateFiledName(entry.getKey()) + " = " + Utils.generateFiledName(entry.getKey())
						+ ";\n\t}\n");
				contentBuild.append("\t" + "public " + Utils.SQLTYPE_TO_JAVATYPE.get(entry.getValue()) + " " + "get"
						+ Utils.generateClassName(entry.getKey()) + "() {" + "\n\t\t" + "return "
						+ Utils.generateFiledName(entry.getKey()) + ";\n\t}\n");
			}

			contentBuild.append("}");
			Utils.writeClassContent(createPackage + File.separator + Utils.generateClassName(table) + ".java",
					contentBuild.toString());
			System.out.println("success");
			// System.out.println(contentBuild.toString());
		}
	}
}

class Utils {
	public final static Map<String, String> IMPORT_PACKAGE = new HashMap<>();
	public final static Map<String, String> SQLTYPE_TO_JAVATYPE = new HashMap<>();
	static {
		SQLTYPE_TO_JAVATYPE.put("INT", "Integer");
		SQLTYPE_TO_JAVATYPE.put("CHAR", "String");
		SQLTYPE_TO_JAVATYPE.put("ENUM", "Enum");
		SQLTYPE_TO_JAVATYPE.put("FLOAT", "Float");
		SQLTYPE_TO_JAVATYPE.put("SMALLINT", "Short");
		SQLTYPE_TO_JAVATYPE.put("INT UNSIGNED", "Integer");
		SQLTYPE_TO_JAVATYPE.put("VARCHAR", "String");
		SQLTYPE_TO_JAVATYPE.put("TIMESTAMP", "Date");
		SQLTYPE_TO_JAVATYPE.put("DATETIME", "Date");

		IMPORT_PACKAGE.put("DATETIME", "import java.util.Date;");
		IMPORT_PACKAGE.put("TIMESTAMP", "import java.util.Date;");
	}

	/**
	 * 
	 * @param tableName
	 * @return 将表名转换为类名,将首字符转为大写
	 */
	public static String generateClassName(String tableName) {
		String className = "";
		String[] split = tableName.split("_");
		for (String string : split) {
			className += (string.substring(0, 1).toUpperCase() + string.substring(1, string.length()));
		}
		return className;
	}

	/**
	 * 将列名转换为字段名,将首字母转为小写,驼峰原则
	 * 
	 * @param columnName
	 * @return
	 */
	public static String generateFiledName(String columnName) {
		String filedName = "";
		String[] split = columnName.split("_");
		for (int i = 0; i < split.length; i++) {
			if (i == 0) {
				filedName += (split[i].substring(0, 1).toLowerCase() + split[i].substring(1, split[i].length()));
			} else {
				filedName += (split[i].substring(0, 1).toUpperCase() + split[i].substring(1, split[i].length()));
			}
		}
		return filedName;
	}

	/**
	 * 传入路径创建包,
	 * 
	 * @param pathName
	 *            格式为xxx.xxx.xxx
	 * @return
	 */
	public static String createPackage(String pathName) {
		String packageName = null;
		try {
			String rootPath = new File("").getCanonicalPath() + File.separator + "src";
			String[] split = pathName.split("\\.");
			for (String string : split) {
				rootPath += File.separator + string;
			}
			File file = new File(rootPath);
			file.mkdirs();
			packageName = file.getCanonicalPath();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return packageName;
	}

	public static void writeClassContent(String pathName, String classContent) {
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(new File(pathName));
			fileOutputStream.write(classContent.getBytes());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				fileOutputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值