自己开发一个Java ORM框架(6)-数据库自动生成Java实体类源码

1. 主要内容

本篇介绍从数据库自动生成Java实体类的代码。

2. 配置文件

数据库连接参数、读取的数据库名、生成实体类的报名、生成实体类的保存地址、日志保存的地址都在配置文件中指明。

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/bank_performance?useUnicode=true&characterEncoding=utf-8
user=root
password=Pass1234
table_schema=bank_performance
entity_package_name=panda.bank.entity
file_save_path=D\:\\Java\\AutoEntity\\
file_log_path=D\:\\Java\\AutoEntity\\

配置文件管理类如下:

package panda.orm.util;
public class Constants {
	public static Property CONFIG_PROPERTY;
	public static String getFormatDateTime(){
		SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formater.format(new Date());
	}
	public static String getLogFormatDateTime(){
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddhhmmss");
		return formater.format(new Date());
	}
	static{
	    Properties fileProperties = new Properties();  
		InputStream inputStream = fileProperties.getClass().getResourceAsStream("/config.properties");  
		CONFIG_PROPERTY=new Property();
        try{  
        	fileProperties.load(inputStream);  
            CONFIG_PROPERTY.setDriver(fileProperties.getProperty("driver"));  
            CONFIG_PROPERTY.setUrl(fileProperties.getProperty("url"));  
            CONFIG_PROPERTY.setUser(fileProperties.getProperty("user"));  
            CONFIG_PROPERTY.setPassword(fileProperties.getProperty("password"));  
            CONFIG_PROPERTY.setTable_schema(fileProperties.getProperty("table_schema"));  
            CONFIG_PROPERTY.setFile_save_path(fileProperties.getProperty("file_save_path"));  
            CONFIG_PROPERTY.setFile_log_path(fileProperties.getProperty("file_log_path"));  
            CONFIG_PROPERTY.setEntity_package_name(fileProperties.getProperty("entity_package_name"));  
        }catch (IOException ex){  
            ex.printStackTrace();  
        }finally{  
            try {
				inputStream.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}  
        }  
	}
}

package panda.orm.util;
public class Property{
	private String driver;
	private String url;
	private String user;
	private String password;
	private String table_schema;
	private String file_save_path;	
	private String file_log_path;
	private String entity_package_name;
        //get set省略

3. 实体类生成器

package panda.orm.util;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import panda.orm.database.MySQLHandler;
import panda.orm.exception.SqlExcuteException;
/**
 * MySql auto generate java classes
 * @author maoge
 * @date 2017.3.23
 */
public class EntityGenerater {
	
	public static void main(String[] args) {
		EntityGenerater.generateClasses();
	}
	
	public static void generateClasses(){
		EntityGenerater eg=new EntityGenerater(Constants.CONFIG_PROPERTY.getTable_schema(),
				Constants.CONFIG_PROPERTY.getEntity_package_name(),Constants.CONFIG_PROPERTY.getFile_save_path());
		eg.init();
		eg.write();
		System.out.println("Panda ORM generate success!");
	}
	
	private Map<String,Set<String>> tables=new HashMap<String,Set<String>>();
	private String table_schema;
	private String entity_package_name;
	private String entity_save_path;
	public EntityGenerater(String table_schema,String entity_package_name,String entity_save_path){
		this.table_schema=table_schema;
		this.entity_package_name=entity_package_name;
		this.entity_save_path=entity_save_path;
	}
	public void init(){
		MySQLHandler hand=new MySQLHandler();
		ResultSet rs=null;
	
		String table_schema =Constants.CONFIG_PROPERTY.getTable_schema();
		
		String sql="select table_name from information_schema.tables where table_schema='"+table_schema+"'";
		tables.clear();
		try {
			rs=hand.query(sql);
			while(rs.next()){
				String tableName=rs.getString("table_name");
				
				Set<String> columns=getColumns(tableName);
				
				tables.put(tableName, columns);
			}
		} catch (Exception ex) {
			new SqlExcuteException(ex.getMessage(),this.getClass().getName(),"sql:",sql);
		}finally{
			hand.sayGoodbye();
		}
	}

	private Set<String> getColumns(String tableName){
		MySQLHandler hand=new MySQLHandler();
		ResultSet rs=null;
		String sql="select * from "+tableName;
		Set<String> columns=new HashSet<String>();
		try {
			rs=hand.query(sql);
			ResultSetMetaData meta=rs.getMetaData();
			int count=meta.getColumnCount();
			for(int i=0;i<meta.getColumnCount();i++){
				columns.add(meta.getColumnName(i+1));
			}
		}catch (Exception ex) {
			new SqlExcuteException(ex.getMessage(),this.getClass().getName(),"sql:",sql);
		}finally{
			hand.sayGoodbye();
		}
		return columns;
	}

	public void write(){
		Iterator iter = tables.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String tableName = (String)entry.getKey();
			Set<String> columns = (Set<String>)entry.getValue();
	
			String entityString=getEntityString(tableName,columns);
	
			try{
				String path=entity_save_path+turnFirstUp(tableName)+".java";
		        File file=new File(path);
		        if(!file.exists())
		            file.createNewFile();
		        FileOutputStream out=new FileOutputStream(file,true);       
		        out.write(entityString.getBytes("utf-8"));
		        out.close();
			}
			catch(Exception ex){
				ex.printStackTrace();
			}	       
		}
	}

	private String getEntityString(String tableName,Set<String> columns){
		StringBuilder sb=new StringBuilder();
	
		sb.append("package "+entity_package_name+";\r\n");
		sb.append("/**\r\n");
	    sb.append("* " + new Date() + "\r\n");
	    sb.append("* Panda ORM atuo generate: " + tableName + " \r\n");
	    sb.append("*/ \r\n");	
	
	    sb.append("public class " + turnFirstUp(tableName) + "{\r\n");
	 
	    for(String colName:columns){
	    	sb.append("\tprivate String "+colName+";\r\n");
	    }
	
	    for(String colName:columns){
	    	sb.append("\tpublic String get"+turnFirstUp(colName)
	    			+"(){\r\n");
	    	sb.append("\t\treturn "+colName+";\r\n");
	    	sb.append("\t}\r\n");
	    	sb.append("\tpublic void set"+turnFirstUp(colName)
	    			+ "(String "+colName+"){\r\n");
	    	sb.append("\t\tthis."+colName+"="+colName+";\r\n");
	    	sb.append("\t}\r\n");
	    }
	    sb.append("}");
		return sb.toString();
	}

    private String turnFirstUp(String str) {
        char[] ch = str.toCharArray();
        if(ch[0]>='a'&&ch[0]<='z'){
            ch[0]=(char)(ch[0]-32);
        }
        return new String(ch);
    }
}

4. 测试

数据库表结构如下

执行下面的方法

public static void main(String[] args) {
		EntityGenerater.generateClasses();
	}
提示如下,并生生成对应实体类代码文件:

Panda ORM generate success!

打开User.java验证如下:

package panda.bank.entity;
/**
* Thu Mar 23 11:30:12 CST 2017
* Panda ORM atuo generate: user 
*/ 
public class User{
	private String user_name;
	private String user_role;
	private String user_job;
	private String user_password;
	private String user_id;
	private String user_department;
	public String getUser_name(){
		return user_name;
	}
	public void setUser_name(String user_name){
		this.user_name=user_name;
	}
	public String getUser_role(){
		return user_role;
	}
	public void setUser_role(String user_role){
		this.user_role=user_role;
	}
	public String getUser_job(){
		return user_job;
	}
	public void setUser_job(String user_job){
		this.user_job=user_job;
	}
	public String getUser_password(){
		return user_password;
	}
	public void setUser_password(String user_password){
		this.user_password=user_password;
	}
	public String getUser_id(){
		return user_id;
	}
	public void setUser_id(String user_id){
		this.user_id=user_id;
	}
	public String getUser_department(){
		return user_department;
	}
	public void setUser_department(String user_department){
		this.user_department=user_department;
	}
}

如有问题请扫码联系我
在这里插入图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页