Java實現自動生成Mysql數據庫表實體類

一個工具類就能夠實現啦,直接看代碼及註釋,很方便理解,從一位博主那裏拿到加上本身優化一部分的java

注:侵刪(忘了原博主信息)mysql

Mysql2EntityGenerator.javaspring

/**
 * @(#) GenEntityMysql.java	2017-2-8 下午3:06:18
 * 
 * Copyright (c) 2014-2015 Diyvc, Inc.
 * 103 Sports Road, Victoria Plaza tower 1104, Tianhe District Guangzhou City, China.
 * All rights reserved.
 *
 */
package com.frend.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Mysql2EntityGenerator {
	
	private String packageOutPath = "com.test.domain";//指定實體生成所在包的路徑
	private String authorName = "frend";//做者名字
	private String tablename = "";//表名
	private String[] colnames; // 列名數組
	private String[] colTypes; //列名類型數組
	private int[] colSizes; //列名大小數組
	private boolean f_util = false; // 是否須要導入包java.util.*
	private boolean f_sql = false; // 是否須要導入包java.sql.*
    
    //數據庫鏈接
	private static final String URL ="jdbc:mysql://127.0.0.1:3306/sqlname";
	private static final String NAME = "root";
	private static final String PASSWORD = "root";
	private static final String DRIVER ="com.mysql.jdbc.Driver";

	/*
	 * 構造函數
	 */
	public Mysql2EntityGenerator(Connection con,String tableName){
		this.tablename = tableName;
    	//建立鏈接
		//查要生成實體類的表
    	String sql = "select * from " + tablename;
    	PreparedStatement pStemt = null;
    	try {
    		
			pStemt = con.prepareStatement(sql);
			ResultSetMetaData rsmd = pStemt.getMetaData();
			int size = rsmd.getColumnCount();	//統計列
			colnames = new String[size];
			colTypes = new String[size];
			colSizes = new int[size];
			for (int i = 0; i < size; i++) {
				colnames[i] = rsmd.getColumnName(i + 1);
				colTypes[i] = rsmd.getColumnTypeName(i + 1);
				
				if(colTypes[i].equalsIgnoreCase("datetime")){
					f_util = true;
				}
				if(colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")){
					f_sql = true;
				}
				colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
			}
			
			String content = parse(colnames,colTypes,colSizes);
			
			try {
				File directory = new File("");
				String outputPath = directory.getAbsolutePath()+ "/src/"+this.packageOutPath.replace(".", "/")+"/"+parseName(tablename) + ".java";
				FileWriter fw = new FileWriter(outputPath);
				PrintWriter pw = new PrintWriter(fw);
				pw.println(content);
				pw.flush();
				pw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
		}
    }

	/**
	 * 功能:生成實體類主體代碼
	 * @param colnames
	 * @param colTypes
	 * @param colSizes
	 * @return
	 */
	private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
		StringBuffer sb = new StringBuffer();
		
		sb.append("package " + this.packageOutPath + ";\r\n");
		sb.append("\r\n");
		//判斷是否導入工具包
		if(f_util){
			sb.append("import java.util.Date;\r\n");
		}
		if(f_sql){
			sb.append("import java.sql.*;\r\n");
		}
		sb.append("import javax.persistence.Column;\r\n");
		sb.append("import javax.persistence.Entity;\r\n");
		sb.append("import javax.persistence.GeneratedValue;\r\n");
		sb.append("import javax.persistence.GenerationType;\r\n");
		sb.append("import javax.persistence.Id;\r\n");
		sb.append("import javax.persistence.Table;\r\n");
		sb.append("import javax.persistence.Temporal;\r\n");
		sb.append("import javax.persistence.TemporalType;\r\n");
		sb.append("import org.springframework.format.annotation.DateTimeFormat;\r\n");
		
		//註釋部分
		sb.append("   /**\r\n");
		sb.append("    * "+tablename+" 實體類\r\n");
		sb.append("    * "+new Date()+" "+this.authorName+"\r\n");
		sb.append("    */ \r\n");
		//實體部分
		sb.append("@Entity\r\n");
		sb.append("@Table(name = \""+tablename+"\")\r\n");
		sb.append("public class " + parseName(tablename) + "{\r\n");
		processAllAttrs(sb);//屬性
		processAllMethod(sb);//get set方法
		sb.append("}\r\n");
		
    	//System.out.println(sb.toString());
		return sb.toString();
	}
	
	/**
	 * 功能:生成全部屬性
	 * @param sb
	 */
	private void processAllAttrs(StringBuffer sb) {
		
		for (int i = 0; i < colnames.length; i++) {
			String column = parseNameNotFirst(colnames[i]);
			if(column.equals("fileSize")){
				System.out.println("here");
			}
			sb.append("\r\n");
			if("id".equals(column)){
				sb.append("\t@Id\r\n");
				sb.append("\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n");
				sb.append("\t@Column(name = \""+colnames[i]+"\", unique = true, nullable = false)\r\n");
			}else{
				sb.append("\t@Column(name = \""+colnames[i]+"\")\r\n");
			}
			if("Date".equals(sqlType2JavaType(colTypes[i]))){
				sb.append("\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\r\n");
				sb.append("\t@Temporal(value = TemporalType.TIMESTAMP)\r\n");
			}
			sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + column + ";\r\n");
		}
		
	}

	/**
	 * 功能:生成get、set方法
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb) {
		
		for (int i = 0; i < colnames.length; i++) {
			sb.append("\r\n");
			sb.append("\tpublic void set" + parseName(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " + 
					parseNameNotFirst(colnames[i]) + "){\r\n");
			sb.append("\t\tthis." + parseNameNotFirst(colnames[i]) + "=" + parseNameNotFirst(colnames[i]) + ";\r\n");
			sb.append("\t}\r\n");
			sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + parseName(colnames[i]) + "(){\r\n");
			sb.append("\t\treturn " + parseNameNotFirst(colnames[i]) + ";\r\n");
			sb.append("\t}\r\n");
		}
		
	}
	
	
	/**
	 * 描述:第一個首字母不大寫,後面大寫
	 * @param name
	 * @return
	 * String
	 */
	public String parseNameNotFirst(String name){
		StringBuffer sb = new StringBuffer();
		String[] array = name.split("_");
		if(array.length > 0){
			for (int i = 0; i < array.length; i++) {
				if (i>0) {
					sb.append(initcap(array[i]));
				}else{
					sb.append(array[i]);
				}
			}
		}
		
		return sb.toString();
	}
	
	/**
	 * 描述:所有首字母大寫
	 * @param name
	 * @return
	 * String
	 */
	public String parseName(String name){
		StringBuffer sb = new StringBuffer();
		String[] array = name.split("_");
		if(array.length > 0){
			for (String string : array) {
				sb.append(initcap(string));
			}
		}
		
		return sb.toString();
	}
	
	/**
	 * 功能:將輸入字符串的首字母改爲大寫(修改爲駝峯法)
	 * @param str
	 * @return
	 */
	private String initcap(String str) {
		
		char[] ch = str.toCharArray();
		if(ch[0] >= 'a' && ch[0] <= 'z'){
			ch[0] = (char)(ch[0] - 32);
		}
		
		return new String(ch);
	}

	/**
	 * 功能:得到列的數據類型
	 * @param sqlType
	 * @return
	 */
	private String sqlType2JavaType(String sqlType) {
		
		if(sqlType.equalsIgnoreCase("bit")){
			return "Boolean";
		}else if(sqlType.equalsIgnoreCase("tinyint")){
			return "Byte";
		}else if(sqlType.equalsIgnoreCase("smallint")){
			return "Short";
		}else if(sqlType.equalsIgnoreCase("int") || sqlType.equalsIgnoreCase("INT UNSIGNED")){
			return "Integer";
		}else if(sqlType.equalsIgnoreCase("bigint")){
			return "Long";
		}else if(sqlType.equalsIgnoreCase("float")){
			return "Float";
		}else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric") 
				|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money") 
				|| sqlType.equalsIgnoreCase("smallmoney")){
			return "Double";
		}else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char") 
				|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar") 
				|| sqlType.equalsIgnoreCase("text")){
			return "String";
		}else if(sqlType.equalsIgnoreCase("datetime")){
			return "Date";
		}else if(sqlType.equalsIgnoreCase("image")){
			return "Blod";
		}
		
		return null;
	}
	
	/**
	 * 出口
	 * TODO
	 * @param args
	 */
	public static void main(String[] args) {
		List<String> tableList = new ArrayList<String>();
		Connection con;
		try {
			Class.forName(DRIVER);
			con = DriverManager.getConnection(URL,NAME,PASSWORD);
			DatabaseMetaData  dm = con.getMetaData();
			ResultSet rs  = dm.getTables(con.getCatalog(), "root", null, new String[]{"TABLE"});
			while(rs.next()) {
				tableList.add(rs.getString("TABLE_NAME"));
			    System.out.println("獲得表名:"+rs.getString("TABLE_NAME"));
			}
			/*if (tableList!=null) {
				for (String tableName : tableList) {
					new GenEntityMysql(con,tableName);
				}
			}*/
			new Mysql2EntityGenerator(con,"file_attachment_info");
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

歡迎斧正,另附源碼及jar包下載地址(下載支持,謝謝)sql

http://download.csdn.net/detail/qq_22876421/9755773數據庫

相關文章
相關標籤/搜索