利用DB2数据字典自动创建表对应的Java Model

本代码是利用DB2数据字典自动创建表对应的Java Model,提高了表格太多,字段太多时手动创建Model时的效率。由于代码是本人写的,所以有任何问题敬请谅解。

 

代码中提供了创建单表Model的方法和对应schema下所有表格model的方法。请用到的网友自行测试。

 

下面直接贴代码:

 

package com.test.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class DBModelCreateManager {
	private Connection con = null;
	private String dbIP;
	private String dbPort;
	private String dbName;
	private String userName;
	private String password;
	public DBModelCreateManager(String dbIP,String dbPort,String userName,String password,String dbName){
		this.dbIP = dbIP;
		this.dbName = dbName;
		this.dbPort = dbPort;
		this.userName = userName;
		this.password = password;
		getConnection();
	}
	private void getConnection(){
		try {
			Class.forName("com.ibm.db2.jcc.DB2Driver");
			String url = "jdbc:db2://"+dbIP+":"+dbPort+"/"+dbName;
			con = DriverManager.getConnection(url, userName, password);
		}
		catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/** * 获取对应表的字段信息 * @param tableName * @return */
	private List<Map<String,String>> getTableColumns(String tableName,String schema){
		List<Map<String,String>> colList = new ArrayList<Map<String,String>>(0);
		if(tableName==null){
			System.err.println("Neither tableName nor schema can be null!");
		} else{
			if(con == null) getConnection();
			if(con != null){
				String sql = "select colname,typename from SYSCAT.COLUMNS where TABNAME='"+tableName.toUpperCase()+"' and TABSCHEMA='"+schema.toUpperCase()+"'" +" order by COLNO";
				PreparedStatement st;
				try {
					st = con.prepareStatement(sql);
					ResultSet rs = st.executeQuery();
					if(rs != null){
						while(rs.next()){
							Map<String,String> map = new HashMap<String, String>();
							map.put("colName",rs.getString("colname"));
							map.put("className", getTypeClass(rs.getString("typename")));
							colList.add(map);
						}
					}
				}
				catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return colList;
	}
	/** * 根据数据库类型获取对应java类型 * @param type * @return */
	private String getTypeClass(String type){
		if(type != null){
			if(type.equalsIgnoreCase("VARCHAR")||type.equalsIgnoreCase("CHARACTER")){
				return "String";
			} else if(type.equalsIgnoreCase("SAMLLINT")||type.equalsIgnoreCase("INTEGER")){
				return "Integer";
			} else if(type.equalsIgnoreCase("DOUBLE")){
				return "double";
			} else if(type.equalsIgnoreCase("BIGINT")){
				return "long";
			} else if(type.equalsIgnoreCase("Date")){
				return "Date";
			} else if(type.equalsIgnoreCase("TIMESTAMP")){
				return "Timestamp";
			}
		}
		return "Object";
	}
	/** * 创建单个表对应的model * @param tableName * @param packagePath * @return * @throws IOException */
	public void createDBModel(String tableName,String packagePath,String schema) throws IOException{
		//创建目录 
        File f = new File("src/"+packagePath.replace(".", "/")+"/"); f.mkdir(); 
        //因为文件是追加写入,所以文件存在则删除 
        String tabName = tableName.toLowerCase(); 
        tabName = tabName.substring(0, 1).toUpperCase()+tabName.substring(1); 
        if(tabName.contains("_")){ 			
            String[] items = tabName.toLowerCase().split("_"); 
            tabName = items[0].substring(0, 1).toUpperCase()+items[0].substring(1); 
            for(int i = 1;i<items.length;i++){ 
                tabName = tabName+items[i].substring(0, 1).toUpperCase()+items[i].substring(1); 
                } 
            } 
            File file = new File("src/"+packagePath.replace(".", "/")+"/"+tabName+".java"); 
            if(file.exists()){ 
                file.delete(); 
            } 
            OutputStreamWriter out = new FileWriter(file,true); 
            List<Map<String,String>> colList = getTableColumns(tableName,schema); 
            StringBuffer fileContent = new StringBuffer("package "+packagePath+";/n"); 
            fileContent.append("import java.util.Date;/n"); 
            fileContent.append("import java.sql.Timestamp;/n"); 
            fileContent.append("public class "+tabName+"{/n"); 
            StringBuffer varStr = new StringBuffer(); 
            StringBuffer methods = new StringBuffer(); 
            for(Iterator<Map<String,String>> it = colList.iterator();it.hasNext();){
                 Map<String,String> obj = it.next(); 
                 String className = obj.get("className"); 
                 String colName = obj.get("colName"); 
                 String[] items = colName.toLowerCase().split("_"); 
                 colName = items[0]; 
                 for(int i = 1;i<items.length;i++){ 
                     colName = colName+items[i].substring(0, 1).toUpperCase()+items[i].substring(1); 
                     } 
                     //变量定义部分 
                     varStr.append("/t"+"private "+className+" "+colName+";/n"); 
                     //set/get方法部分 
                     methods.append("/t"+"public void set"+colName.substring(0, 1).toUpperCase()+colName.substring(1)+"("+className+" "+colName+"){/n");
                      methods.append("/t/t this."+colName+" = "+colName+";/n"); methods.append("/t}/n/n"); 
                      methods.append("/t"+"public "+className+" get"+colName.substring(0, 1).toUpperCase()+colName.substring(1)+"(){/n"); 
                      methods.append("/t/t return this."+colName+";/n"); methods.append("/t}/n/n"); 
            } 
            fileContent.append(varStr.toString()+"/n"); 
            fileContent.append(methods.toString()); 
            fileContent.append("}"); 
            //写入文件 out.write(fileContent.toString()); out.close(); 
        } 
        /** 
        * 为对应schema下的所有表创建model 
        * @param schema 
        * @param packagePath 
        * @throws IOException 
        */ 
        public void createModelForSchema(String schema,String packagePath) throws IOException{ 
            List<String> tableList = new ArrayList<String>(0); 
            if(schema==null){ 
                System.err.println("Schema can not be null!");
            }else{ 
                if(con == null) 
                    getConnection(); 
                if(con != null){
                    String sql = "select tabname from SYSCAT.TABLES where TABSCHEMA='"+schema.toUpperCase()+"'"; 
                    PreparedStatement st;
                    try { 
                        st = con.prepareStatement(sql); 
                        ResultSet rs = st.executeQuery(); 
                        if(rs != null){ 
                            while(rs.next()){ 
                                tableList.add(rs.getString("tabname")); 						
                            }
                        } 
                    } catch (SQLException e) { 
                        e.printStackTrace(); 
                    } 
                } 
            } 
            for(Iterator<String> it = tableList.iterator();it.hasNext();){ 
                String tableName = it.next(); 
                createDBModel(tableName, packagePath,schema); 
            } 
        } 
        
    }

 

 

下面这个是我自己测试生成的一个model的类代码。

 

package com.test.model;
import java.util.Date;
import java.sql.Timestamp;
public class PatchAdvisory{
	private long uid;
	private Integer packageSid;
	private long swcatUid;
	private String vendorId;
	private String vendorTitle;
	private String rating;
	private Timestamp vendorReleaseDate;
	private Timestamp receiveDate;
	private String sourceAvailable;
	private Timestamp publishDate;
	private String productType;
	private String vendor;
	private String product;
	private String version;
	private String releasename;
	private String underlyingOs;
	private String architecture;
	private String createdby;
	private String datasource;
	private String lastmodifiedby;
	private String deleted;
	private String audUser;
	private String audType;
	private Timestamp audTime;
	private Timestamp lastmodifiedtime;
	private String validFlag;
	private String vendorUrl;
	private String sourceUrl;
	private String primaryUrl;
	private String dq;
	private String updatePending;
	private Timestamp ratingDate;
	private String securityflag;
	private String crcCode;
	private String ratingDesignator;
	private Integer varianceCode;
	public void setUid(long uid){
		this.uid = uid;
	}
	public long getUid(){
		return this.uid;
	}
	public void setPackageSid(Integer packageSid){
		this.packageSid = packageSid;
	}
	public Integer getPackageSid(){
		return this.packageSid;
	}
	public void setSwcatUid(long swcatUid){
		this.swcatUid = swcatUid;
	}
	public long getSwcatUid(){
		return this.swcatUid;
	}
	public void setVendorId(String vendorId){
		this.vendorId = vendorId;
	}
	public String getVendorId(){
		return this.vendorId;
	}
	public void setVendorTitle(String vendorTitle){
		this.vendorTitle = vendorTitle;
	}
	public String getVendorTitle(){
		return this.vendorTitle;
	}
	public void setRating(String rating){
		this.rating = rating;
	}
	public String getRating(){
		return this.rating;
	}
	public void setVendorReleaseDate(Timestamp vendorReleaseDate){
		this.vendorReleaseDate = vendorReleaseDate;
	}
	public Timestamp getVendorReleaseDate(){
		return this.vendorReleaseDate;
	}
	public void setReceiveDate(Timestamp receiveDate){
		this.receiveDate = receiveDate;
	}
	public Timestamp getReceiveDate(){
		return this.receiveDate;
	}
	public void setSourceAvailable(String sourceAvailable){
		this.sourceAvailable = sourceAvailable;
	}
	public String getSourceAvailable(){
		return this.sourceAvailable;
	}
	public void setPublishDate(Timestamp publishDate){
		this.publishDate = publishDate;
	}
	public Timestamp getPublishDate(){
		return this.publishDate;
	}
	public void setProductType(String productType){
		this.productType = productType;
	}
	public String getProductType(){
		return this.productType;
	}
	public void setVendor(String vendor){
		this.vendor = vendor;
	}
	public String getVendor(){
		return this.vendor;
	}
	public void setProduct(String product){
		this.product = product;
	}
	public String getProduct(){
		return this.product;
	}
	public void setVersion(String version){
		this.version = version;
	}
	public String getVersion(){
		return this.version;
	}
	public void setReleasename(String releasename){
		this.releasename = releasename;
	}
	public String getReleasename(){
		return this.releasename;
	}
	public void setUnderlyingOs(String underlyingOs){
		this.underlyingOs = underlyingOs;
	}
	public String getUnderlyingOs(){
		return this.underlyingOs;
	}
	public void setArchitecture(String architecture){
		this.architecture = architecture;
	}
	public String getArchitecture(){
		return this.architecture;
	}
	public void setCreatedby(String createdby){
		this.createdby = createdby;
	}
	public String getCreatedby(){
		return this.createdby;
	}
	public void setDatasource(String datasource){
		this.datasource = datasource;
	}
	public String getDatasource(){
		return this.datasource;
	}
	public void setLastmodifiedby(String lastmodifiedby){
		this.lastmodifiedby = lastmodifiedby;
	}
	public String getLastmodifiedby(){
		return this.lastmodifiedby;
	}
	public void setDeleted(String deleted){
		this.deleted = deleted;
	}
	public String getDeleted(){
		return this.deleted;
	}
	public void setAudUser(String audUser){
		this.audUser = audUser;
	}
	public String getAudUser(){
		return this.audUser;
	}
	public void setAudType(String audType){
		this.audType = audType;
	}
	public String getAudType(){
		return this.audType;
	}
	public void setAudTime(Timestamp audTime){
		this.audTime = audTime;
	}
	public Timestamp getAudTime(){
		return this.audTime;
	}
	public void setLastmodifiedtime(Timestamp lastmodifiedtime){
		this.lastmodifiedtime = lastmodifiedtime;
	}
	public Timestamp getLastmodifiedtime(){
		return this.lastmodifiedtime;
	}
	public void setValidFlag(String validFlag){
		this.validFlag = validFlag;
	}
	public String getValidFlag(){
		return this.validFlag;
	}
	public void setVendorUrl(String vendorUrl){
		this.vendorUrl = vendorUrl;
	}
	public String getVendorUrl(){
		return this.vendorUrl;
	}
	public void setSourceUrl(String sourceUrl){
		this.sourceUrl = sourceUrl;
	}
	public String getSourceUrl(){
		return this.sourceUrl;
	}
	public void setPrimaryUrl(String primaryUrl){
		this.primaryUrl = primaryUrl;
	}
	public String getPrimaryUrl(){
		return this.primaryUrl;
	}
	public void setDq(String dq){
		this.dq = dq;
	}
	public String getDq(){
		return this.dq;
	}
	public void setUpdatePending(String updatePending){
		this.updatePending = updatePending;
	}
	public String getUpdatePending(){
		return this.updatePending;
	}
	public void setRatingDate(Timestamp ratingDate){
		this.ratingDate = ratingDate;
	}
	public Timestamp getRatingDate(){
		return this.ratingDate;
	}
	public void setSecurityflag(String securityflag){
		this.securityflag = securityflag;
	}
	public String getSecurityflag(){
		return this.securityflag;
	}
	public void setCrcCode(String crcCode){
		this.crcCode = crcCode;
	}
	public String getCrcCode(){
		return this.crcCode;
	}
	public void setRatingDesignator(String ratingDesignator){
		this.ratingDesignator = ratingDesignator;
	}
	public String getRatingDesignator(){
		return this.ratingDesignator;
	}
	public void setVarianceCode(Integer varianceCode){
		this.varianceCode = varianceCode;
	}
	public Integer getVarianceCode(){
		return this.varianceCode;
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值