利用DB2数据字典自动创建表对应的Java Model
2011-06-07 16:39
471 查看
本代码是利用DB2数据字典自动创建表对应的Java Model,提高了表格太多,字段太多时手动创建Model时的效率。由于代码是本人写的,所以有任何问题敬请谅解。
代码中提供了创建单表Model的方法和对应schema下所有表格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; } }
相关文章推荐
- 利用在线工具根据JSon数据自动生成对应的Java实体类
- 【java项目实践】在eclipse中使用利用mybatis-generator自动生成Model、Dao、mapping代码
- 利用jQuery的ajax得到的数据动态创建树,然后点击数节点,把对应的节点的节点信息赋值给某一个div,是上一篇的升级版
- 传入Java对象 自动创建动态表 并录入数据
- 从redis 自动拿数据对应到java 设备上时候出现过得一个错误。记录
- 通过JPA来自动创建Model类与数据中表对应
- 利用反射把DataTable自动赋值到Model实体(自动识别数据类型)
- json解析出来的数据库是字典和数组的组合,创建一个model来接收解析数据
- 利用反射把DataTable自动赋值到Model实体(自动识别数据类型)
- 利用JDBC连接池封装类自动根据mysql数据库生成对应的model类
- oracle自动生成数据字典,生成创建语句
- IOS 利用Model 反射属性 自动 创建表 插入 查询 修改
- java基本数据类型及其所对应对象的自动装箱,new,valueof操作研究
- 利用python操作android的xml资源文件,让其按照中文自动生成对应中文首字母加起来的名字,并且根据中文在java类里面替代对应的中文
- 实用技巧:利用SQL Server的扩展属性自动生成数据字典
- 传入Java对象 自动创建动态表 并录入数据
- 考虑大对象:利用 JAVA 操作 DB2 Universal Database 中的 LOB 数据
- JAVA数据类型与DB2、Oracle、Sybase以及SQL Server对应关系
- Java Object to Data Model Data Type Mapping, java数据类型与数据库数据类型的对应
- 利用SQL Server的扩展属性自动生成数据字典