自动更具数据库表来生成javaclass文件的小工具_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 自动更具数据库表来生成javaclass文件的小工具

自动更具数据库表来生成javaclass文件的小工具

 2013/7/10 3:35:27  q821424508  程序员俱乐部  我要评论(0)
  • 摘要:快下班了,写点东西吧,这个小工具写的有几个月了,中间做个小demo的时候还用到了,自我感觉用着挺爽的,很小,一个类,很快,全自动,很方便,直接修改配置就行。不多说了。packagecom.base;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileWriter;importjava.io.IOException;importjava.sql.Connection;importjava.sql
  • 标签:文件 工具 Java 数据库 数据 数据库表 class

快下班了,写点东西吧,

这个小工具写的有几个月了,中间做个小demo的时候还用到了,

自我感觉用着挺爽的,很小,一个类,很快,全自动,很方便,直接修改配置就行。

?

不多说了。

class="java">package com.base;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author q821424508@sina.com
 * @version 1.0
 * 
 */

public class Table2Entity {

	private static String Entity2Store = "src/com/hung/model";// 以项目名为根目录
	//private static String tablesSql = "SELECT table_name FROM information_schema.tables WHERE table_schema ='common' AND NOT table_name  LIKE 'sys%'";
	private static String tablesSql = "SELECT table_name FROM information_schema.tables WHERE table_schema ='common' ";
	private static List<String> tables = new ArrayList<String>();
	private static String url = "jdbc:mysql://127.0.0.1/common?useUnicode=true&characterEncoding=utf8";
	private static String driver = "com.mysql.jdbc.Driver";
	private static String username = "admin";
	private static String password = "123456";
	private static String sql = "select * from ";
	private static String author = "q821424508";

	private static Connection conn = null;
	private static Statement stat = null;

	public static void main(String[] args) {
		System.out.println("---begin---");
		init();
		table2Entity();
		System.out.println("---end---");
	}

	/**
     */

	private static void init() {
		File f = new File(Entity2Store);
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	/**
     */

	private static void table2Entity() {
		tables = getTables();
		if (null != tables && tables.size() > 0) {
			for (String tableName : tables) {
				doTable2Entity(tableName);
			}
		}
	}

	/**
     */

	private static void doTable2Entity(String tableName) {
		String sql1 = sql + tableName;
		System.out.println("tableName = " + tableName + "\n");
		conn = getConn();
		try {
			stat = conn.createStatement();
			ResultSet rs = stat.executeQuery(sql1);
			ResultSetMetaData metaDate = rs.getMetaData();
			int count = metaDate.getColumnCount();

			File classFile = getCF(tableName);

			FileWriter fw = new FileWriter(classFile, true);
			BufferedWriter bw = new BufferedWriter(fw);

			StringBuffer sbFields = new StringBuffer();
			
			//toString 方法
			StringBuffer toString = new StringBuffer("\tpublic String toString(){\n");
			toString.append("\t\tString str=\"{");
			
			for (int j = 0; j < count; j++) {
				String columnName = metaDate.getColumnName(j + 1);
				int type = metaDate.getColumnType(j + 1);
				System.out.println(columnName + " : " + type);
				sbFields.append(column2field(columnName, type));
				
				toString.append(""+column2fieldName(columnName)+":'\" + "+column2fieldName(columnName)+" + \"',\" + \"");
				
			}
			
			bw.write(sbFields.toString());
			
			//toString.replace(toString.length()-1, toString.length(), "");
			
			toString.replace(toString.length()-8, toString.length(), "");
			
			toString.append("\"'}\";\n");
			
			toString.append("\t\treturn str;\n\t}\n");
			
			
			bw.write(toString.toString());
			
			
			bw.write("\n}\n");
			bw.close();
			fw.close();

			System.out.println("---------------------------------");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * @param columnName
	 * @param type
	 * @return
	 */

	private static String column2field(String columnName, int type) {
		String field = "";
		String getseter = "";

		String fieldName = column2fieldName(columnName);

		field = getField(fieldName, type);
		getseter = getGetseter(fieldName, type);

		return field + "\n" + getseter;

	}

	/**
	 * @param columnName
	 * @param type
	 * @return
	 */

	private static String getGetseter(String columnName, int type) {
		String filedName = firstChar2Upper(columnName);
		StringBuffer sb = new StringBuffer("");
		switch (type) {
		case Types.BIGINT:
			sb.append("\tpublic long get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(long ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.INTEGER:
			sb.append("\tpublic int get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(int ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;

		case Types.CHAR:
			sb.append("\tpublic String get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(String ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.DATE:
			sb.append("\tpublic Date get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(Date ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.DOUBLE:
			sb.append("\tpublic double get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(double ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.FLOAT:
			sb.append("\tpublic float get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(float ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.LONGNVARCHAR:

			sb.append("\tpublic String get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(String ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.LONGVARCHAR:
			sb.append("\tpublic String get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(String ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.NVARCHAR:
			sb.append("\tpublic String get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(String ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.SMALLINT:
			sb.append("\tpublic int get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(int ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.TIMESTAMP:
			sb.append("\tpublic Date get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(Date ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.TINYINT:
			sb.append("\tpublic int get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(int ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.NUMERIC:
			sb.append("\tpublic long get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(long ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.VARCHAR:
			sb.append("\tpublic String get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(String ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;
		case Types.BLOB:
			sb.append("\tpublic byte[] get");
			sb.append(filedName);
			sb.append("(){\n");
			sb.append("\t\treturn ");
			sb.append("this.");
			sb.append(columnName);
			sb.append(";\n");
			sb.append("\t}\n");

			sb.append("\tpublic void set");
			sb.append(filedName);
			sb.append("(byte[] ");
			sb.append(columnName);
			sb.append("){\n");
			sb.append("\t\t");
			sb.append("this.");
			sb.append(columnName);
			sb.append("=" + columnName);
			sb.append(";\n");
			sb.append("\t}\n\n");
			break;

		default:
			break;
		}
		return sb.toString();

	}

	/**
	 * @param columnName
	 * @param type
	 * @return
	 */

	private static String getField(String columnName, int type) {

		StringBuffer sb = new StringBuffer("\tprivate ");
		switch (type) {
		case Types.BIGINT:
			sb.append("long ").append(columnName);
			break;
		case Types.INTEGER:
			sb.append("int ").append(columnName);
			break;
		case Types.NUMERIC:
			sb.append("long ").append(columnName);
			break;
		case Types.CHAR:
			sb.append("String ").append(columnName);
			break;
		case Types.DATE:
			sb.append("Date ").append(columnName);
			break;
		case Types.DOUBLE:
			sb.append("double ").append(columnName);
			break;
		case Types.FLOAT:
			sb.append("float ").append(columnName);
			break;
		case Types.LONGNVARCHAR:
			sb.append("String ").append(columnName);
			break;
		case Types.LONGVARCHAR:
			sb.append("String ").append(columnName);
			break;
		case Types.NVARCHAR:
			sb.append("String ").append(columnName);
			break;
		case Types.SMALLINT:
			sb.append("int ").append(columnName);
			break;
		case Types.TIMESTAMP:
			sb.append("Date ").append(columnName);
			break;
		case Types.TINYINT:
			sb.append("int ").append(columnName);
			break;
		case Types.VARCHAR:
			sb.append("String ").append(columnName);
			break;
		case Types.BLOB:
			sb.append("byte[] ").append(columnName);
			break;

		default:
			System.err.println("columnName = " + columnName + " : type = "
					+ type);
			break;
		}

		sb.append(";\n");
		return sb.toString();

	}

	/**
	 * @param tableName
	 * @return
	 */

	private static File getCF(String tableName) {

		File classFile = new File(Entity2Store + File.separator
				+ table2EntityName(tableName) + ".java");

		try {
			FileWriter fw = new FileWriter(classFile);
			BufferedWriter bw = new BufferedWriter(fw);
			String cr = getCopyRight();
			String packagePath = getPachagePath();
			String importPath = getImportPath();
			String clazzName = getClassName(tableName);

			bw.write(cr);
			bw.write(packagePath);
			bw.write(importPath);
			bw.write(clazzName);

			bw.flush();
			bw.close();
			fw.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return classFile;

	}

	/**
	 * @param tableName
	 * @return
	 */

	private static String getClassName(String tableName) {
		String className = table2EntityName(tableName);
		className = "public class " + className + " implements Serializable{\n";
		className += "\n\t" + "private static final long serialVersionUID ="
				+ (tableName + (Math.random() * 90000000 + 10000000)).hashCode()+"l";
		className += ";\n\n";

		return className;

	}

	/**
	 * @param tableName
	 * @return
	 */

	private static String table2EntityName(String tableName) {
		tableName = column2fieldName(tableName);
		tableName = firstChar2Upper(tableName);
		return tableName;

	}

	/**
	 * @param tableName
	 * @return
	 */

	private static String firstChar2Upper(String tableName) {
		String firstChar = tableName.substring(0, 1);
		String entityName = tableName.replaceFirst(firstChar, firstChar
				.toUpperCase());
		return entityName;

	}

	/**
	 * @param tableName
	 * @return
	 */

	private static String column2fieldName(String columnName) {
		columnName = columnName.toLowerCase();
		while (columnName.contains("_")) {
			int i = columnName.indexOf('_');
			String char2Upper = columnName.substring(i + 1, i + 2);
			columnName = columnName.replaceFirst("_" + char2Upper, char2Upper
					.toUpperCase());
		}

		while (columnName.contains("-")) {
			int i = columnName.indexOf('-');
			String char2Upper = columnName.substring(i + 1, i + 2);
			columnName = columnName.replaceFirst("-" + char2Upper, char2Upper
					.toUpperCase());
		}

		return columnName;

	}

	/**
	 * @return
	 */

	private static String getImportPath() {

		StringBuffer sb = new StringBuffer();
		sb.append("import java.io.Serializable;\n");
		sb.append("import java.util.Date;\n\n");

		return sb.toString();

	}

	/**
	 * @return
	 */

	private static String getPachagePath() {
		return "package " + Entity2Store.replace("src/", "").replace('/', '.')
				+ ";\n\n";

	}

	/**
	 * @return
	 */

	private static String getCopyRight() {

		StringBuffer cr = new StringBuffer("/**");
		cr.append("\n");
		cr.append("*/");
		cr.append("\n");
		cr.append("\n");
		cr.append("\n");
		return cr.toString();

	}

	/**
	 * @return
	 */

	private static List<String> getTables() {

		conn = getConn();
		try {
			stat = conn.createStatement();
			ResultSet rs = stat.executeQuery(tablesSql);
			while (rs.next()) {
				tables.add(rs.getString(1));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return tables;

	}

	/**
	 * @return
	 */

	private static Connection getConn() {

		if (null != conn) {
			return conn;
		}
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();

		} catch (SQLException e) {
			e.printStackTrace();

		}
		return conn;

	}

}

// end

?

其实这小工具早就想放出来了,但是考虑下,netbean自带的有这个工具,eclipse好像也有(需要插件)

myeclipse更不用说了,必须有,不过要是不知道的人,用着也挺不方便,

?

为什么要写这个东西?

我们开发的时候用的是eclipse,尝试了安装插件来完成,但是没有成功,之前在上家公司的时候,boss用一个晚上搞出来的东西,自己也想试试,其实自从boss写出来之后一直有这个冲动,boss是用python写的,

这次做项目的机会,自己写了一个,

总共花费2天不到的时间吧,看来boss就是boss,不得不服

?

先说明一下,这个小工具并不是支持全部sql类型,有需要的可以自己扩充,

原来我想把这个工具优化一下,写成配置文件的方式,后来就一拖再拖,直到现在。

?

欢迎随便转发,使用,修改,不过请注明原文出出。

欢迎拍砖,

?

?

发表评论
用户名: 匿名