欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

生成实体类

程序员文章站 2022-06-14 23:03:14
...

生成实体类

开发工具与关键技术:MyEclipse 10、java
作者:梁添荣
撰写时间:2019-6-08

做项目是不免需要创建实体类与数据库表联系,但如果每一张表一张表去创建的话,不免浪费时间,所有做一个util实现生成实体类
思路如下:
1.	明白实体类结构
2.	创建连接,获取表名,进而获取其列的属性
3.	按照实体类的结构的,写出实体类文件
package com.gx.ts;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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;
public class CreateEntityUtil {
	private final String DRIVER="com.mysql.jdbc.Driver";
	private final String URL="jdbc:mysql://localhost:3306/demo?serverTimezone=GMT%2B8";
	private final String USER="root";
	private final String PASSWORD="root";	
	String packageName="com/gx/po";//包名
	Connection con;
	DatabaseMetaData md;
	ResultSet rs;
	ResultSetMetaData rsm;
	PreparedStatement ps;
//获取所有表名
	public void TableList(){	
		try {
			Class.forName(DRIVER);
			con=DriverManager.getConnection(URL,USER,PASSWORD);
			md=con.getMetaData();//获取数据库的元数据	
			rs=md.getTables(con.getCatalog(), null, "%", null);//获取可在给定类别中使用的表的描述
			while(rs.next()){		
				String tableName=rs.getString("TABLE_NAME");//获取表名			
				ColProperties(tableName);
			}
		} catch (ClassNotFoundException e) {		
			e.printStackTrace();
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				md=null;
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
//获取表里的列的属性
	public void ColProperties(String tableName){
		try {
			Class.forName(DRIVER);
			con=DriverManager.getConnection(URL,USER,PASSWORD);
			ps=con.prepareStatement("select * from "+tableName);
			rsm=ps.getMetaData();//表的结构
			int size=rsm.getColumnCount();//多少列
			//设置列名、列名类型、列名大小数组长度
			String[] colNames=new String[size];
			String[] colTypes=new String[size];
			int[] colSizes=new int[size];
			//获取列的属性
			for (int i = 0; i < size; i++) {
				colNames[i]=rsm.getColumnName(i+1);//列名
				colTypes[i]=LowerColTypes(rsm.getColumnTypeName(i+1));//列类型,获取到的是大写所以转小写。
//ps:若知道各个类型需要的jra包,可以把jra包也输入文件
				//记录是否引入jra包
//				if(colTypes[i].equals("image")||colTypes[i].equals("text")){
//					f_sql=true;
//				}else{
//					f_sql=false;
//				}
//				if(colTypes[i].equals("datetime")){
//					f_util=true;
//				}else{
//					f_util=false;
//				}
				colSizes[i]=rsm.getColumnDisplaySize(i+1);
			}
			//传递表名、列名数组、列类型数组、列大小数组
			CreateEntiy(Inincap(tableName),colNames,colTypes,colSizes);
		} catch (ClassNotFoundException e) {	
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				rsm=null;
				ps.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}	
	}
//创建实体类,保存到文件夹
	public void CreateEntiy(String tableName,String[] colNames,String[] colTypes,int[] colSizes){
		String path=System.getProperty("user.dir")+"/src/"+packageName;
		File folder=new File(path);
		if(!folder.exists()){
			folder.mkdir();
		}
		FileWriter fw = null;
		try {
			String fileName=path+"/"+tableName+".java";
			File file=new File(fileName);
			fw=new FileWriter(file);
			StringBuffer sb=new StringBuffer();
		//开始添加内容
			//包名
			sb.append("package\t"+packageName.replace("/", ".")+";");///r/n??
//			if(f_util==true){
//				sb.append("import java.util.Date;\r\n");
//			}
//			if(f_sql==true){
//				sb.append("import java.sql.*;\r\n");
//			}
			sb.append("\r\nimport java.io.Serializable;\r\n");
			//class
			sb.append("public class "+tableName+" implements Serializable{\r\n");
			//添加变量
			for (int i = 0; i < colTypes.length; i++) {
				sb.append("\tprivate "+TypeCast(colTypes[i])+" "+colNames[i]+";\r\n");
			}
			//添加构造器
			sb.append("\tpublic "+tableName+"(){}\r\n\tpublic "+tableName+"(");
			for (int i = 0; i < colTypes.length; i++) {
				String colType=TypeCast(colTypes[i]);
				if(i<colTypes.length-1){
					sb.append(colType+" "+colNames[i]+", ");
				}else{
					sb.append(colType+" "+colNames[i]+"){\r\n\t");
				}
			}
			for (int i = 0; i < colTypes.length; i++) {
				sb.append("this."+colNames[i]+"="+colNames[i]+";\r\n\t");
			}
			sb.append("}\r\n");
			//添加get、set
			for (int i = 0; i < colTypes.length; i++) {		
				String colType=TypeCast(colTypes[i]);
				sb.append("\tpublic "+colType+" get"+Inincap(colNames[i])+"(){\r\n\treturn "+colNames[i]+";\r\n\t}\r\n");	
				sb.append("\tpublic void set"+Inincap(colNames[i])+"("+colType+" "+colNames[i]+"){\r\n\tthis."+colNames[i]+" ="+colNames[i]+";\r\n\t}\r\n");
			}
			sb.append("}");
			fw.write(sb.toString());
			fw.flush();	
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
//列名转小写
	public String LowerColTypes(String colTypes){
		String colType=colTypes.toLowerCase();
		return colType;
	}
//列名首字母转小写
	public String Lowercase(String colNames){		
		String colNames2=colNames.substring(0,1).toLowerCase()+colNames.substring(1);
		return colNames2;
	}
//表名首字母转大写
	public String Inincap(String tableName){
		String tableName2=tableName.substring(0,1).toUpperCase()+tableName.substring(1);
		return tableName2;
	}
//转换列名类型
	public String TypeCast(String colTypes){
//ps:此处说明,switch参数是String类型的话必须是JavaSE-1.7
	如果此前没有,更改为JavaSE-1.7可能会使项目报错,可以用if语句代替
		switch(colTypes){
		case "bigint":return "long";
		case "binary":return "byte[]";
		case "bit": return "boolean";
		case "blob": return "byte[]";
		case "bool": return "bool";
		case "boolean": return "boolean";
		case "char": return "String";
		case "date": return "Date";
		case "datetime": return "Timestamp";
		case "decimal": return "double";
		case "double": return "double";
		case "enum": return "String";
		case "float": return "float";
		case "int": return "int";
		case "longblob": return "byte[]";
		case "longtext": return "String";
		case "mediumblob": return "byte[]";
		case "mediumint": return "";
		case "mediumtext": return "String";
		case "numeric": return "double";
		case "real":return "double";
		case "set":return "String";
		case "smallint":return "short";
		case "text":return "String";
		case "time":return "Date";
		case "tiemstamp":return "Date";
		case "tinyblob":return "byte[]";
		case "tinyint":return "byte[]";
		case "tinytext":return "String";
		case "varbinary":return "byte[]";
		case "varchar":return "String";
		case "year":return "Date";
		}
		return colTypes;
		
	}
	public static void main(String[] args) {
		CreateEntityUtil createEntityUtil=new CreateEntityUtil();
		createEntityUtil.TableList();
		System.out.print("创建完成!");
	}
}