根据数据库表结构生成相应的Java实体类

生成java实体类 同时被 3 个专栏收录
1 篇文章 0 订阅
1 篇文章 0 订阅
3 篇文章 0 订阅

根据数据库表结构生成相应的Java实体类

思路:

  • 1、创建数据库连接
  • 2、获取数据库表、表注释
  • 3、获取数据库表中字段名、字段类型、字段注释
  • 4、构建StringBuffer缓存
  • 5、写入文件
  • 6、关闭连接、输入流等等

使用方式:

  • 1、修改数据源连接信息
  • 2、修改实体配置信息
  • 3、测试
package GenerPro;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
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.util.Date;

/**
 * 根据数据库表结构生成相应的JavaBean
 *
 * 思路
 * 1、创建数据库连接
 * 2、获取数据库表、表注释
 * 3、获取数据库表中字段名、字段类型、字段注释
 * 4、构建StringBuffer缓存
 * 5、写入文件
 * 6、关闭连接、输入流等等
 *
 * @author shihongxin
 * @Date 2020/0929
 */
public class GenerOraclePro {
	// 数据库连接
	private static final String URL = "jdbc:oracle:thin:@192.168.100.247:1521:orcl";
	private static final String NAME = "data_manage";
	private static final String PASS = "data123";
	private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
	
	// 需配置项
	private String packageOutPath = "E:/pro/";// 生成实体文件所在位置
	private String tableName = "MT_DS_TABLE";//数据库中的表名
	private String packageName = "com.zebone.dataManage.common.vo";//实体类所在的包
	private String authorName = "shihongxin";// 作者名字
	private boolean f_util = true; // 是否需要导入包java.util.*
	private boolean f_sql = true; // 是否需要导入包java.sql.*

	
	private String[] colsPre = { "F_NB_", "F_VC_", "F_CR_", "F_DT_"};
	private String[] colnames; // 列名数组
	private String[] colTypes; // 列名类型数组
	private int[] colSizes; // 列名大小数组
	private String pkFiled = null;  //表主键
	private Connection con = null;
	private Statement pStemt = null;
	private ResultSet rs = null;
	private ResultSetMetaData rsmd = null;
	
	public GenerOraclePro() {
		connect();
		getTableInfo(tableName);
		colseConnect();
	}
	/**
    * 1、创建数据库连接
    */
	private void connect() {
		try {
			Class.forName(DRIVER);
			con = DriverManager.getConnection(URL, NAME, PASS);
			pStemt = (Statement) con.createStatement();
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	private void colseConnect() {
		try {
			if (con != null) {
				con.close();
				con = null;
			}
			if (pStemt != null) {
				pStemt.close();
				pStemt = null;
			}
		} catch (SQLException e) {
				e.printStackTrace();
		}
	}

	/**
    * 获取单个数据库表信息
    */
	private void getTableInfo(String tableName) {
		int size = 0;
		String sql = "SELECT * FROM " + tableName;
		try {
			rs = pStemt.executeQuery(sql);
			rsmd = rs.getMetaData();
			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("date") || colTypes[i].equalsIgnoreCase("timestamp")) {
					f_util = true;
				}
				if (colTypes[i].equalsIgnoreCase("blob") || colTypes[i].equalsIgnoreCase("char")) {
					f_sql = true;
				}
				colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
			}
			pkFiled = getTablePk(tableName);
			//获取单张数据库表注释
			String tableComment = getTableComment(tableName);

			//获取单张数据库表的所有列信息
			StringBuffer tempSb = getColsInfo(tableName);

			//生成JavaBean文件
			genFile(tableName, getSb(tableName, tableComment, tempSb));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取表主键
	 * @param TableName
	 * @return
	 */
	public String getTablePk(String TableName){
		String str = null;
		String sql = "Select  b.Column_Name pkFiled From user_Constraints a,user_Cons_Columns b Where a.Constraint_Type = 'P' "
				+ " and a.Constraint_Name = b.Constraint_Name And a.Owner = b.Owner And a.table_name = b.table_name And a.table_name=upper('"+TableName+"') ";
		try {
			rs = pStemt.executeQuery(sql);
			while (rs.next()) {
				str = rs.getString("pkFiled");
				if (null != str && str.indexOf("\r\n") != -1) {
					str = str.replace("\r\n", "");
				}
				if (null != str && str.indexOf("\n") != -1) {
					str = str.replace("\n", "");
				}
			 }
		} catch (SQLException e) {
				e.printStackTrace();
		}
		return str;
	}	
	
	/**
    * 获取单张数据库表注释
    * @param tableName
    * @return
    */
	private String getTableComment(String tableName) {
		String str = "";
		String sql = "select * from user_tab_comments where table_name = '"+ tableName + "'";
		try {
			rs = pStemt.executeQuery(sql);
			while (rs.next()) {
				str = rs.getString("comments");
				if (null != str && str.indexOf("\r\n") != -1) {
					str = str.replace("\r\n", "");
				}
				if (null != str && str.indexOf("\n") != -1) {
					str = str.replace("\n", "");
				}
			 }
		} catch (SQLException e) {
				e.printStackTrace();
		}
		return str;
	}
	
	/**
    * 获取单张数据库表的所有列信息
    * @param tableName
    */
	private StringBuffer getColsInfo(String tableName) {
		StringBuffer temp = new StringBuffer();
		//组装列信息
		for (int i = 0; i < colnames.length; i++) {
			temp.append("\r\n\t/*"+getColsName(colnames[i])+" - "+getColComment(tableName, colnames[i])+"*/\r\n");/** PK_EMPI_LOG_ID - 个人基本信息主键 */
			if(pkFiled!=null && pkFiled.equals(getColsName(colnames[i]))){
				//System.out.println(pkFiled+"==="+getColsName(colnames[i]));
				temp.append("\t@PK\r\n");
			}
			temp.append("\t@Field(value=\""+getColsName(colnames[i])+"\")\r\n");
			//temp.append("\tprivate " + getColsType(colTypes[i]) + " "+ captureName(getColsName(colnames[i]),false) + ";  //" + getColComment(tableName, colnames[i]) + "\r\n");
			temp.append("\tprivate " + getColsType(colTypes[i]) + " "+ captureName(getColsName(colnames[i]),false) + ";\r\n");
		}
		//组装get(),set()
		for(int j = 0; j < colnames.length; j++){
			String colname = captureName(getColsName(colnames[j]),false);
			String colnameUp = captureName(getColsName(colnames[j]),true);
			temp.append("\n\tpublic void set" + colnameUp + "(" + getColsType(colTypes[j]) + " " + colname + "){\r\n");
			temp.append("\t\tthis." + colname + "=" + colname + ";\r\n");
			temp.append("\t}\r\n");
			temp.append("\n\tpublic " + getColsType(colTypes[j]) + " get" + colnameUp + "(){\r\n");
			temp.append("\t\treturn " + colname + ";\r\n");
			temp.append("\t}\r\n");
		}
		return temp;
	}

	/**
    * 获取列类型
    * @param sqlType
    * @return
    */
	private String getColsType(String sqlType) {
		if (sqlType.equalsIgnoreCase("binary_double")) {
			return "double";
		} else if (sqlType.equalsIgnoreCase("binary_float")) {
			return "float";
		} else if (sqlType.equalsIgnoreCase("blob")) {
			return "byte[]";
		} else if (sqlType.equalsIgnoreCase("blob")) {
			return "byte[]";
		} else if (sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("nvarchar2") || sqlType.equalsIgnoreCase("varchar2")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("date") || sqlType.equalsIgnoreCase("timestamp") || sqlType.equalsIgnoreCase("timestamp with local time zone") || sqlType.equalsIgnoreCase("timestamp with time zone")) {
			return "Date";
		} else if (sqlType.equalsIgnoreCase("number")) {
			return "Long";
		}
		return "String";
	}
	/**
    * 获取列名
    *
    * @param str
    * @return
    */
	private String getColsName(String str) {
		for (String temp : colsPre) {
			int preIndex = str.indexOf(temp);
			if (preIndex >= 0) {
				str = str.substring(preIndex + temp.length());
				str = str.replace("_", "").toLowerCase();
			}
		}
		return str;
	}
	/**
    * 获取列注释
    *
    * @param tableName
    * @param columnName
    * @return
    */
	private String getColComment(String tableName, String columnName) {
		String str = "";
		String sql = "select comments from USER_COL_COMMENTS where table_name= '" + tableName + "' and column_name= '" + columnName + "'";
		try {
			rs = pStemt.executeQuery(sql);
			while (rs.next()) {
				str = rs.getString("comments");
				if (null != str && str.indexOf("\r\n") != -1) {
					str = str.replace("\r\n", "");
				}
				if (null != str && str.indexOf("\n") != -1) {
					str = str.replace("\n", "");
				}
			 }
		} catch (SQLException e) {
				e.printStackTrace();
		}
		return str;
	}

	/**

    * 构建StringBuffer缓存
    * @param tableName
    * @param tableComment
    * @param colSb
    * @return
    */
	private StringBuffer getSb(String tableName, String tableComment,StringBuffer colSb) {
		StringBuffer sb = new StringBuffer();
		sb.append("package " + this.packageName + ";\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 com.zebone.platform.modules.dao.build.au.Table;\r\n");
		sb.append("import com.zebone.platform.modules.dao.build.au.Field;\r\n");
		sb.append("import com.zebone.platform.modules.dao.build.au.PK;\r\n");
		
		sb.append("\r\n");
		// 注释部分
		sb.append("\t/**\r\n");
		sb.append("    * " + tableName + " 实体类              " + tableComment + "\r\n");
		sb.append("    * " + new Date() + "\r\n");
		sb.append("    * @author " + this.authorName + "\r\n");
		sb.append("    */ \r\n");
		// 实体部分
		sb.append("\r\n\r\n@Table(value=\""+tableName+"\")");
		sb.append("\r\npublic class " + captureName(tableName,true) + "{\r\n");
		sb.append("\tprivate static final long serialVersionUID = 1L;\r\n");
		sb.append(colSb);
		sb.append("}\r\n");
		return sb;
	}

	/**
	 * 生成JavaBean文件
    *
    * @param content
    */
	private void genFile(String tableName, StringBuffer content) {
		try {
			String outputPath = this.packageOutPath + captureName(tableName,true) + ".java";
			FileWriter fw = new FileWriter(outputPath);
			PrintWriter pw = new PrintWriter(fw);
			pw.println(content);
			pw.flush();
			pw.close();

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

	/**
	 * 驼峰命名/首字母大写
	 * @param name
	 * @param flag 首字母是否大写
	 * @return
	 */
	public static String captureName(String name,boolean isUp) {

		//char[] cs = name.toCharArray();
		//首字母是小写的需要大写
		//if(cs[0] >= 97 && cs[0] <= 122) {
		//	cs[0] -= 32;
		//}
		//return String.valueOf(cs);
		
		//public static String changeToJavaFiled(String field) {
			String[] fields = name.toLowerCase().split("_");
			StringBuilder sbuilder = new StringBuilder(fields[0]);
			for (int i = 1; i < fields.length; i++) {
				char[] cs = fields[i].toCharArray();
				cs[0] -= 32;
				sbuilder.append(String.valueOf(cs));
			}
			name = sbuilder.toString();
			
			if(isUp){
				char[] cs = name.toCharArray();
				//首字母是小写的需要大写
				if(cs[0] >= 97 && cs[0] <= 122) {
					cs[0] -= 32;
				}
				name = String.valueOf(cs);
			}
			
			return name;
			
		//}
	}

	/**
    * 出口 TODO
    *
    * @param args
	 */
	public static void main(String[] args) {
		System.err.println("*****开始连接数据库,组装信息,生成文件.........");
		new GenerOraclePro();
		System.err.println("*****结束.........");
	}
}
  • 0
    点赞
  • 0
    评论
  • 4
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页

打赏作者

落熙君夏沫

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值