zoukankan      html  css  js  c++  java
  • SprinfJdbcTemplate+SpringMVC 代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)

    代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)

      原文地址:  http://jilongliang.iteye.com/blog/2262070
    
    Java代码  收藏代码
    1. package com.flong.codegenerator;  
    2.   
    3. import java.sql.Connection;  
    4. import java.sql.DatabaseMetaData;  
    5. import java.sql.PreparedStatement;  
    6. import java.sql.ResultSet;  
    7. import java.sql.ResultSetMetaData;  
    8. import java.sql.SQLException;  
    9. import java.sql.Timestamp;  
    10. import java.text.SimpleDateFormat;  
    11. import java.util.ArrayList;  
    12. import java.util.Date;  
    13. import java.util.HashMap;  
    14. import java.util.List;  
    15. import java.util.Map;  
    16. import java.util.Set;  
    17.   
    18. import org.apache.commons.lang3.StringUtils;  
    19. /*** 
    20.  *@Author:liangjilong 
    21.  *@Date:2015年12月5日下午12:25:12 
    22.  *@Email:jilongliang@sina.com 
    23.  *@Version:1.0 
    24.  *@CopyRight(c)Flong Intergrity Ltd. 
    25.  *@Desction:★★★★★★★★★★★★★★★代码生成器实现思路★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 
    26.  * 
    27.  *   ★★在快速开发的过程中,为了节省时间和成本很多人都会开发自己的代码生成器,而且成为程序员开发过程中必不可少的神器. 
    28.  *   ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 
    29.  *    第一种:先有数据库表,然后通过jdbc链接数据库再读取表的字段等属性出来生成Entity,Dao,Service,Controller,JSP等代码 
    30.  *   这种必须是有数据库和表的思想,通过程序去读取数据库表的属性等信息,然后组织代码通过文件流生成文件. 
    31.  *    
    32.  *   ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 
    33.  *   第二种:已经设计好数据库表文档,把所有表的字段属性配置到EXCEL或者CSV格式的文件通过JXL/POI技术去读取文件的字段实现 
    34.  *   Entity,Dao,Service,Controller,JSP,在过程中会借助Freemaker,Velocity去实现.三层和jsp,然后通过一下ORM(hibernate, 
    35.  *   ibatis,myibatis等)技术逆向生成数据库表.这种是无数据库表的思想. 在生成java的代码一般不建议建ORM映射主从表关系,通过 
    36.  *   SQL去建立关系,为啥?因为在一些大型的公司如:银行,阿里巴巴,电信等公司,很多项目开发过程中在数据库表很少建立表关系的 
    37.  *   因为在些业务复杂的情况下通过SQL和程序控制的解决方案比ORM映射关系方案占优势.比如优化性能/维护/灵活性更加好等. 
    38.  *   ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 
    39.  *    
    40.  *   此程序以MySQL为主,未实现其他数据库.此程序可以再优化的,为了有些初学者,就不作太多的处理和优化.一些高手会编程更好的生 
    41.  *   成器,此程序只提供参考和学习,如有什么问题,可以多指出.共同学习和进步.谢谢!~ 
    42.  *   ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 
    43.  */  
    44. @SuppressWarnings("all")  
    45. public class CodeGenerator {  
    46.       
    47.        
    48.     /*************************变量****Begin************************************/  
    49.     private static final String myEmail="jilongliang@sina.com";//Email  
    50.     private static final String Version="1.0";//版本  
    51.     private static final String Description=" ";//描述  
    52.       
    53.     public static final String ENTER = " ";//换行  
    54.     public static final String TAB = "    ";//tab空格.  
    55.     public static final String NAME = "NAME";  
    56.     public static final String TABLE_CAT = "TABLE_CAT";//表 catalog  
    57.     public static final String TABLE_SCHEM = "TABLE_SCHEM";//表 schema  
    58.     public static final String TABLE_NAME = "TABLE_NAME";//表名  
    59.     public static final String TABLE_TYPE = "TABLE_TYPE";//表类型  
    60.     public static final String REMARKS = "REMARKS";//表注释  
    61.     public static final String TYPE = "TYPE";//表的类型  
    62.     public static final String SIZE = "SIZE";//大小  
    63.     public static final String CLASS = "CLASS";//类别  
    64.       
    65.     /*************************变量****End************************************/  
    66.       
    67.     public static final String NOW_DATE = new SimpleDateFormat("yyyy-MM-dd").format(new Date());  
    68.     /***************获取数据库的配置连接************/  
    69.     public static final String DB_NAME = PropertiesHelper.getValueByKey("jdbc.url").substring(  
    70.                                          PropertiesHelper.getValueByKey("jdbc.url").lastIndexOf("/")+1,  
    71.                                          PropertiesHelper.getValueByKey("jdbc.url").indexOf("?") == -1?  
    72.                                          PropertiesHelper.getValueByKey("jdbc.url").length():  
    73.                                          PropertiesHelper.getValueByKey("jdbc.url").indexOf("?"));  
    74.     //从配置获取工程的报名路径  
    75.     public static final String ROOT_PACKAGE = PropertiesHelper.getValueByKey("rootPackage");  
    76.     //获取作者.  
    77.     public static final String AUTHOR = PropertiesHelper.getValueByKey("author");  
    78.     //忽略表的后缀.  
    79.     public static final List<String> IGNORE_TABLE_PREFIX = new ArrayList<String>();  
    80.   
    81.     /*******定义代码块*******/  
    82.     static {  
    83.         String ignoreTablePrefix = PropertiesHelper.getValueByKey("ignoreTablePrefix");  
    84.         if(ignoreTablePrefix.length() > 0) {  
    85.             String[] ignoreTablePrefixs = ignoreTablePrefix.split("\s*\,\s*");  
    86.             for (String elem : ignoreTablePrefixs) {  
    87.                 IGNORE_TABLE_PREFIX.add(elem);  
    88.             }  
    89.         }  
    90.     }  
    91.   
    92.     /*** 
    93.      * 生成实体类的代码 
    94.      * @param table 
    95.      * @throws Exception 
    96.      */  
    97.     public void createEntityClass(String table) throws Exception {  
    98.         String tableConstantName = getTableConstantName(table);  
    99.           
    100.         String className = getClassName(tableConstantName);  
    101.         StringBuilder buffer = new StringBuilder();  
    102.         buffer.append("package " + ROOT_PACKAGE + ".entity;").append(ENTER);  
    103.         buffer.append("import java.util.Date;").append(ENTER);  
    104.         buffer.append("import com.flong.commons.persistence.Entity;").append(ENTER);  
    105.         buffer.append("import com.flong.commons.persistence.annotation.Column;").append(ENTER);  
    106.         buffer.append("import com.flong.commons.persistence.annotation.Id;").append(ENTER);  
    107.         buffer.append("import com.flong.commons.persistence.annotation.Relation;").append(ENTER);  
    108.         buffer.append("import com.flong.commons.persistence.annotation.Table;").append(ENTER);  
    109.         buffer.append(ENTER);  
    110.         buffer.append(ENTER);  
    111.         buffer.append("/**  * @Created:" + NOW_DATE + "  * @Author " + AUTHOR + " ");  
    112.         buffer.append(" * @Version:").append(Version).append(ENTER);  
    113.         buffer.append(" * @Description:").append(className).append(ENTER);  
    114.         buffer.append(" * @Email:").append(myEmail).append(" */");  
    115.         buffer.append(ENTER);  
    116.         buffer.append("@Relation(" + className + ".TABLE)");  
    117.         buffer.append(ENTER);  
    118.         buffer.append("public class " + className + " extends Entity {");  
    119.         buffer.append(ENTER);  
    120.         buffer.append(ENTER);  
    121.         buffer.append(TAB);  
    122.         buffer.append("/** 表名常量 */");  
    123.         buffer.append(ENTER);  
    124.         buffer.append(TAB);  
    125.         buffer.append("public static final String TABLE = Table." + tableConstantName + ";");  
    126.         buffer.append(ENTER);  
    127.         buffer.append(ENTER);  
    128.         buffer.append(TAB);  
    129.         buffer.append("/**");  
    130.         buffer.append(ENTER);  
    131.         buffer.append(TAB);  
    132.         buffer.append(" * 列名常量");  
    133.         buffer.append(ENTER);  
    134.         buffer.append(TAB);  
    135.         buffer.append(" */");  
    136.         buffer.append(ENTER);  
    137.         for (Map<String, Object> col : getCols(table)) {  
    138.             String colName = col.get(NAME).toString().toUpperCase();  
    139.             buffer.append(TAB);//生成字段变量  
    140.             buffer.append("public static final String COL_" + colName + " = "" + colName + "";//"+col.get(REMARKS));  
    141.             buffer.append(ENTER);  
    142.         }  
    143.         buffer.append(ENTER);  
    144.         buffer.append(TAB);  
    145.         buffer.append("/**");  
    146.         buffer.append(ENTER);  
    147.         buffer.append(TAB);  
    148.         buffer.append(" * 列属性");  
    149.         buffer.append(ENTER);  
    150.         buffer.append(TAB);  
    151.         buffer.append(" */");  
    152.           
    153.         String tablePrimaryKeys = getTablePrimaryKeys(table);//如果是主键  
    154.           
    155.         //if(col.get(NAME).toString().equalsIgnoreCase("ID")) {  
    156.         if(tablePrimaryKeys!=null){   
    157.             buffer.append(ENTER+TAB);  
    158.               
    159.             //如果主键不为空的时候就给一个@Id注解.  
    160.             //如果是hibernate的可以给其他的注解,如@GeneratedValue(strategy = GenerationType.IDENTITY)   @SequenceGenerator等  
    161.             //并要在包的下面头部导入  
    162.             //import javax.persistence.Column;  
    163.             //import javax.persistence.Entity;  
    164.             //import javax.persistence.GeneratedValue;  
    165.             //import javax.persistence.GenerationType;  
    166.             //import javax.persistence.Id;  
    167.             //import javax.persistence.Table;  
    168.             buffer.append("@Id");  
    169.             //这里不赋值给,因为下面这个for循环有一个.  
    170.             //sb.append("@Column(COL_" + tablePrimaryKeys + ")");  
    171.         }  
    172.         for (Map<String, Object> col : getCols(table)) {  
    173.             buffer.append(TAB);  
    174.             buffer.append(ENTER);  
    175.             buffer.append(TAB);  
    176.             buffer.append("@Column(COL_" + col.get(NAME).toString().toUpperCase() + ")");  
    177.             buffer.append(ENTER);  
    178.             buffer.append(TAB);  
    179.             buffer.append("private ");  
    180.             //这行代码的意思就是说,如果找到数据库表的字段是为ID的时候,或后缀有_ID的就认为是主键,并且忽略大小写就给一个Long  
    181.             //在实际过程中应该判断是它的字段是不是为了PrimaryKey才设为Long才适合.  
    182.             //if(col.get(NAME).toString().equalsIgnoreCase("ID") || col.get(NAME).toString().toUpperCase().endsWith("_ID")) {  
    183.             if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {  
    184.                 buffer.append("Date");  
    185.             } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {  
    186.                 buffer.append(col.get(CLASS));  
    187.             } else {  
    188.                 buffer.append(Class.forName(col.get(CLASS).toString()).getSimpleName());  
    189.             }  
    190.             //sb.append(" " + getFieldName(col.get(NAME).toString()) + ";");  
    191.             buffer.append(" " + col.get(NAME).toString() + ";");  
    192.             buffer.append(ENTER);  
    193.         }  
    194.         buffer.append(ENTER);  
    195.         for (Map<String, Object> col : getCols(table)){  
    196.             buffer.append(TAB);  
    197.             buffer.append("public ");  
    198.             if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {  
    199.                 buffer.append("Date");  
    200.             } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {  
    201.                 buffer.append(col.get(CLASS));  
    202.             } else {  
    203.                 buffer.append(Class.forName(col.get(CLASS).toString()).getSimpleName());  
    204.             }  
    205.             buffer.append(" ").append("get").append(col.get(NAME).toString().replaceFirst("\b(\w)|\s(\w)", col.get(NAME).toString().substring(0,1).toUpperCase()));  
    206.             buffer.append("() {");  
    207.             buffer.append(ENTER);  
    208.             buffer.append(TAB);  
    209.             buffer.append(TAB);  
    210.             buffer.append("return ").append(col.get(NAME).toString()).append(";");  
    211.             buffer.append(ENTER);  
    212.             buffer.append(TAB);  
    213.             buffer.append("}");  
    214.             buffer.append(ENTER);  
    215.             buffer.append(TAB);  
    216.             buffer.append("public void ").append("set").append(col.get(NAME).toString().replaceFirst("\b(\w)|\s(\w)", col.get(NAME).toString().substring(0,1).toUpperCase()));  
    217.             buffer.append("(");  
    218.             if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {  
    219.                 buffer.append("Date");  
    220.             } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {  
    221.                 buffer.append(col.get(CLASS));  
    222.             } else {  
    223.                 buffer.append(Class.forName(col.get(CLASS).toString()).getSimpleName());  
    224.             }  
    225.             buffer.append(" ").append(col.get(NAME).toString());  
    226.             buffer.append(") {");  
    227.             buffer.append(ENTER);  
    228.             buffer.append(TAB);  
    229.             buffer.append(TAB);  
    230.             buffer.append("this.").append(col.get(NAME).toString()).append(" = ").append(col.get(NAME).toString()).append(";");  
    231.             buffer.append(ENTER);  
    232.             buffer.append(TAB);  
    233.             buffer.append("}");  
    234.             buffer.append(ENTER);  
    235.         }  
    236.         buffer.append("}");  
    237.         buffer.append(ENTER);  
    238.         FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\.""/") + "/entity/" + className + ".java", buffer.toString());  
    239.     }  
    240.       
    241.     /*** 
    242.      * 生成dao接口interface类的代码 
    243.      * @param table 
    244.      * @throws Exception 
    245.      */  
    246.     public void createDaoClass(String table) throws Exception {  
    247.         String className = getClassName(getTableConstantName(table));  
    248.           
    249.         String objectName = StringUtils.uncapitalize(className);  
    250.           
    251.         StringBuilder buffer = new StringBuilder();  
    252.         buffer.append("package " + ROOT_PACKAGE + ".dao;").append(ENTER);  
    253.         buffer.append("import java.io.Serializable;").append(ENTER);  
    254.         buffer.append("import java.util.List;").append(ENTER);  
    255.         buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);  
    256.         buffer.append("import com.flong.commons.persistence.dao.EntityDao;").append(ENTER);  
    257.         buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);  
    258.           
    259.         buffer.append(ENTER);  
    260.         buffer.append(ENTER);  
    261.         buffer.append("/**  * @Created:" + NOW_DATE + "  * @Author " + AUTHOR + " ");  
    262.         buffer.append(" * @Version:").append(Version).append(ENTER);  
    263.         buffer.append(" * @Description:").append(className).append(ENTER);  
    264.         buffer.append(" * @Email:").append(myEmail).append(" */");  
    265.         buffer.append(ENTER);  
    266.           
    267.         buffer.append("public interface " + className + "Dao extends EntityDao<" + className + "> {").append(ENTER);  
    268.           
    269.           
    270.         buffer.append("/**查询*/").append(ENTER);  
    271.         buffer.append(" public List<"+className+"> list(SimplePage simplePage,"+className+" "+objectName+");").append(ENTER);  
    272.           
    273.         buffer.append("/**保存数据*/").append(ENTER);  
    274.         buffer.append(" public void saveData("+className+" "+objectName+");").append(ENTER);  
    275.           
    276.         buffer.append("/**更新数据*/").append(ENTER);  
    277.           
    278.         buffer.append(" public void updateData("+className+" "+objectName+");").append(ENTER);  
    279.           
    280.         buffer.append("/**删除数据*/").append(ENTER);  
    281.           
    282.         buffer.append(" public void deleteData(Long pk);").append(ENTER);  
    283.           
    284.         buffer.append(ENTER);  
    285.         buffer.append(ENTER);  
    286.         buffer.append("}");  
    287.         buffer.append(ENTER);  
    288.         FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\.""/") + "/dao/" + className + "Dao.java", buffer.toString());  
    289.     }  
    290.       
    291.     /*** 
    292.      * 生成dao的实现类的代码 
    293.      * @param table 
    294.      * @throws Exception 
    295.      */  
    296.     public void createDaoImplClass(String table) throws Exception {  
    297.         String className = getClassName(getTableConstantName(table));  
    298.         String objectName =  StringUtils.uncapitalize(className);  
    299.         String tableName = StringUtils.lowerCase(getTableConstantName(table));//获取表名  
    300.           
    301.         StringBuilder buffer = new StringBuilder();  
    302.         buffer.append("package " + ROOT_PACKAGE + ".dao.impl;").append(ENTER);  
    303.         buffer.append("import java.io.Serializable;").append(ENTER);  
    304.         buffer.append("import org.apache.commons.lang3.StringUtils;").append(ENTER);  
    305.         buffer.append("import org.springframework.stereotype.Repository;").append(ENTER);  
    306.         buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);  
    307.         buffer.append("import com.flong.commons.persistence.dao.impl.EntityDaoSupport;").append(ENTER);  
    308.         buffer.append("import com.flong.modules.dao."+className+"Dao;").append(ENTER);  
    309.         buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);  
    310.    
    311.           
    312.         buffer.append(ENTER);  
    313.         buffer.append(ENTER);  
    314.         buffer.append("/**  * @Created:" + NOW_DATE + "  * @Author " + AUTHOR + " ");  
    315.         buffer.append(" * @Version:").append(Version).append(ENTER);  
    316.         buffer.append(" * @Description:").append(className).append(ENTER);  
    317.         buffer.append(" * @Email:").append(myEmail).append(" */");  
    318.         buffer.append(ENTER);  
    319.         buffer.append("@Repository");//这个是spring的注解  
    320.         buffer.append(ENTER);  
    321.         buffer.append("public class " + className + "DaoImpl extends EntityDaoSupport<" + className + "> implements " + className + "Dao {");  
    322.           
    323.           
    324.         buffer.append("/**查询*/").append(ENTER);  
    325.         buffer.append(" public List<"+className+"> list(SimplePage simplePage,"+className+" "+objectName+"){").append(ENTER);  
    326.           
    327.         buffer.append(ENTER);  
    328.           
    329.         String mergeField= "";//合并字段.  
    330.           
    331.         //--遍历获取列,并拼接字符串,SQL的查询列,查询不建议用*去查询表的所有列.  
    332.         for (Map<String, Object> col : getCols(table)){  
    333.               
    334.             //  
    335.             if(col.get(NAME).toString()!=null){  
    336.                 mergeField +=col.get(NAME).toString()+",";//合并字段并用,隔开字段名  
    337.             }  
    338.         }  
    339.         //去掉最后一个,号然后拼接成一个完成的select查询字段  
    340.         if(mergeField!=null){  
    341.             mergeField = mergeField.substring(0, mergeField.length()-1);  
    342.         }  
    343.           
    344.         buffer.append("    String sql = ").append("" select "+mergeField+" from ").append(tableName).append(" where 1=1 " ").append(ENTER);//这个TABLE是实体类的变量  
    345.         //daoQuery这个是底层封装的一个接口,自个可以更加自己需求封装.  
    346.         buffer.append("    List<"+className+"> list= daoQuery.query(sql,"+className+".class,simplePage);").append(ENTER);  
    347.         buffer.append(" return list;").append(ENTER);  
    348.           
    349.         buffer.append("}").append(ENTER);//查询的结束{  
    350.           
    351.           
    352.         buffer.append("/**保存数据*/").append(ENTER);  
    353.         buffer.append(" public void saveData("+className+" "+objectName+"){").append(ENTER);  
    354.         buffer.append("   try {").append(ENTER);  
    355.         buffer.append("      saveOrUpdate("+className+");").append(ENTER);  
    356.         buffer.append("   } catch (DaoAccessException e) {").append(ENTER);  
    357.         buffer.append("      e.printStackTrace();").append(ENTER);  
    358.         buffer.append("  }").append(ENTER);  
    359.           
    360.         buffer.append("}");  
    361.           
    362.           
    363.         buffer.append("/**更新数据*/").append(ENTER);  
    364.           
    365.         buffer.append(" public void updateData("+className+" "+objectName+"){").append(ENTER);  
    366.           
    367.         buffer.append("   try {").append(ENTER);  
    368.         buffer.append("      saveOrUpdate("+className+");").append(ENTER);  
    369.         buffer.append("   } catch (DaoAccessException e) {").append(ENTER);  
    370.         buffer.append("      e.printStackTrace();").append(ENTER);  
    371.         buffer.append("  }").append(ENTER);  
    372.           
    373.         buffer.append("}");  
    374.           
    375.           
    376.         buffer.append("/**删除数据*/").append(ENTER);  
    377.         buffer.append(" public void deleteData(Long pk){").append(ENTER);  
    378.           
    379.         buffer.append("   try {").append(ENTER);  
    380.         buffer.append("      delete(pk);").append(ENTER);  
    381.         buffer.append("   } catch (DaoAccessException e) {").append(ENTER);  
    382.         buffer.append("      e.printStackTrace();").append(ENTER);  
    383.         buffer.append("  }").append(ENTER);  
    384.           
    385.           
    386.         buffer.append("}");  
    387.           
    388.         buffer.append(ENTER);  
    389.         buffer.append(ENTER);  
    390.         buffer.append("}");  
    391.         buffer.append(ENTER);  
    392.         FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\.""/") + "/dao/impl/" + className + "DaoImpl.java", buffer.toString());  
    393.     }  
    394.   
    395.       
    396.     /*** 
    397.      * 创建Service的接口 
    398.      * createServiceClass 
    399.      * @param table 
    400.      */  
    401.     public void createServiceClass(String table) {  
    402.   
    403.         String className = getClassName(getTableConstantName(table));  
    404.         String objectName = StringUtils.uncapitalize(className);  
    405.           
    406.         StringBuilder buffer = new StringBuilder();  
    407.           
    408.         buffer.append("package " + ROOT_PACKAGE + ".service;");  
    409.   
    410.         buffer.append("import java.io.Serializable;").append(ENTER);  
    411.         buffer.append("import java.util.List;").append(ENTER);  
    412.         buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);  
    413.         buffer.append("import com.flong.commons.persistence.dao.EntityDao;").append(ENTER);  
    414.         buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);  
    415.           
    416.           
    417.         buffer.append(ENTER);  
    418.         buffer.append(ENTER);  
    419.         buffer.append("/**  * @Created:" + NOW_DATE + "  * @Author " + AUTHOR + " ");  
    420.         buffer.append(" * @Version:").append(Version).append(ENTER);  
    421.         buffer.append(" * @Description:").append(className).append(ENTER);  
    422.         buffer.append(" * @Email:").append(myEmail).append(" */");  
    423.         buffer.append(ENTER);  
    424.         buffer.append("public interface " + className + "Service {");  
    425.           
    426.         buffer.append("/**查询*/").append(ENTER);  
    427.         buffer.append(" public List<"+className+"> list(SimplePage simplePage,"+className+" "+objectName+");").append(ENTER);  
    428.           
    429.         buffer.append("/**保存数据*/").append(ENTER);  
    430.         buffer.append(" public void saveData("+className+" "+objectName+");").append(ENTER);  
    431.           
    432.         buffer.append("/**更新数据*/").append(ENTER);  
    433.           
    434.         buffer.append(" public void updateData("+className+" "+objectName+");").append(ENTER);  
    435.           
    436.         buffer.append("/**删除数据*/").append(ENTER);  
    437.           
    438.         buffer.append(" public void deleteData(Long pk);").append(ENTER);  
    439.           
    440.         buffer.append(ENTER);  
    441.         buffer.append(ENTER);  
    442.         buffer.append("}");  
    443.         buffer.append(ENTER);  
    444.         FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\.""/") + "/service/" + className + "Service.java", buffer.toString());  
    445.       
    446.     }  
    447.   
    448.     /*** 
    449.      * 创建Service层的实现类 
    450.      * 这里跟Dao的实现的都继承了EntityDaoSupport,主要是为了体现三层service分成的体验保留. 
    451.      * createServiceImplClass 
    452.      * @param table 
    453.      */  
    454.     public void createServiceImplClass(String table) {  
    455.   
    456.         String className = getClassName(getTableConstantName(table));  
    457.       
    458.         String objectName = StringUtils.uncapitalize(className);  
    459.           
    460.         StringBuilder buffer = new StringBuilder();  
    461.           
    462.         buffer.append("package " + ROOT_PACKAGE + ".service.impl;");  
    463.         buffer.append("import java.io.Serializable;").append(ENTER);  
    464.         buffer.append("import java.util.List;").append(ENTER);  
    465.         buffer.append("import org.springframework.beans.factory.annotation.Autowired;").append(ENTER);  
    466.         buffer.append("import org.springframework.stereotype.Service;").append(ENTER);  
    467.         buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);  
    468.         buffer.append("import com.flong.commons.persistence.dao.impl.EntityDaoSupport;").append(ENTER);  
    469.         buffer.append("import com.flong.modules.dao."+className+"Dao;").append(ENTER);  
    470.         buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);  
    471.         buffer.append("import com.flong.modules.service."+className+"Service;").append(ENTER);  
    472.           
    473.            
    474.         buffer.append(ENTER);  
    475.         buffer.append(ENTER);  
    476.         buffer.append("/**  * @Created:" + NOW_DATE + "  * @Author " + AUTHOR + " ");  
    477.         buffer.append(" * @Version:").append(Version).append(ENTER);  
    478.         buffer.append(" * @Description:").append(className).append(ENTER);  
    479.         buffer.append(" * @Email:").append(myEmail).append(" */");  
    480.         buffer.append(ENTER);  
    481.         buffer.append("@Service");  
    482.         buffer.append(ENTER);  
    483.         buffer.append("public class " + className + "ServiceImpl extends EntityDaoSupport  implements " + className + "Service {").append(ENTER);  
    484.         buffer.append("@Autowired "+className+"Dao "+objectName+"Dao;");  
    485.           
    486.         buffer.append("/**查询*/").append(ENTER);  
    487.         buffer.append(" public List<"+className+"> list(SimplePage simplePage,"+className+" "+objectName+"){").append(ENTER);  
    488.         buffer.append("     return "+objectName+"Dao.list(simplePage,"+objectName+");").append(ENTER);  
    489.         buffer.append("}").append(ENTER);//查询的结束{  
    490.           
    491.           
    492.           
    493.         buffer.append("/**保存数据*/").append(ENTER);  
    494.         buffer.append(" public void saveData("+className+" "+objectName+"){").append(ENTER);  
    495.               
    496.         buffer.append(    objectName+"Dao.saveData("+objectName+");").append(ENTER);  
    497.         buffer.append("}");  
    498.           
    499.         buffer.append("/**更新数据*/").append(ENTER);  
    500.           
    501.         buffer.append(" public void updateData("+className+" "+objectName+"){").append(ENTER);  
    502.         buffer.append(    objectName+"Dao.updateData("+objectName+");").append(ENTER);  
    503.           
    504.         buffer.append("}");  
    505.         buffer.append("/**删除数据*/").append(ENTER);  
    506.           
    507.         buffer.append(" public void deleteData(Long pk){").append(ENTER);  
    508.         buffer.append(    objectName+"Dao.deleteData(pk);").append(ENTER);  
    509.         buffer.append("}");  
    510.           
    511.           
    512.         buffer.append(ENTER);  
    513.         buffer.append(ENTER);  
    514.         buffer.append("}");  
    515.         buffer.append(ENTER);  
    516.         FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\.""/") + "/service/impl/" + className + "ServiceImpl.java", buffer.toString());  
    517.       
    518.     }  
    519.       
    520.       
    521.     /*** 
    522.      * 创建控制层类Controller 
    523.      * @param table 
    524.      */  
    525.     public void createControllerClass(String table){  
    526.         //类名  
    527.         String className = getClassName(getTableConstantName(table));  
    528.         //通过 org.apache.commons.lang3.StringUtils的uncapitalize方法把类名第一个字母转换成小写  
    529.         String objectName = StringUtils.uncapitalize(className);  
    530.           
    531.         //通过 org.apache.commons.lang3.StringUtils的lowerCase方法把类名整个单词转化成小写然后为springmvc的路径返回jsp请求.  
    532.         String BASE_PATH="modules/"+StringUtils.lowerCase(className)+"/";//modules+模块名  
    533.           
    534.         StringBuilder buffer = new StringBuilder();  
    535.         /*******处理这个导入需要的类*********/  
    536.         buffer.append("import java.util.List;").append(ENTER);  
    537.         buffer.append("import javax.servlet.http.HttpServletRequest;").append(ENTER);  
    538.         buffer.append("import javax.servlet.http.HttpServletResponse;").append(ENTER);  
    539.         buffer.append("import org.springframework.beans.factory.annotation.Autowired;").append(ENTER);  
    540.         buffer.append("import org.springframework.stereotype.Controller;").append(ENTER);  
    541.         buffer.append("import org.springframework.web.bind.annotation.RequestMapping;").append(ENTER);  
    542.         buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);  
    543.         buffer.append("import com.flong.commons.web.BaseController;").append(ENTER);  
    544.         buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);  
    545.         buffer.append("import com.flong.modules.service."+className+"Service;").append(ENTER);  
    546.            
    547.         buffer.append(ENTER);  
    548.         buffer.append(ENTER);  
    549.         buffer.append("/**  * @Created:" + NOW_DATE + "  * @Author " + AUTHOR + " ");  
    550.         buffer.append(" * @Version:").append(Version).append(ENTER);  
    551.         buffer.append(" * @Description:").append(className).append(ENTER);  
    552.         buffer.append(" * @Email:").append(myEmail).append(" */");  
    553.         buffer.append(ENTER);  
    554.         buffer.append(ENTER);  
    555.         buffer.append("@Controller").append(ENTER);  
    556.         buffer.append("@RequestMapping(""+StringUtils.lowerCase(className)+"")");  
    557.         buffer.append(ENTER);  
    558.         buffer.append("public class " + className + "Controller extends BaseController {");  
    559.         buffer.append(ENTER);  
    560.         buffer.append(ENTER);  
    561.         buffer.append(" @Autowired "+className+"Service " +className+"Service");//注入Service层的接口Name  
    562.         buffer.append(ENTER);  
    563.           
    564.         //创建一个默认的查询..  
    565.         buffer.append(ENTER);  
    566.         buffer.append("   @RequestMapping(value="list")").append(ENTER);  
    567.         buffer.append("   public String list("+className+" "+objectName+",SimplePage simplePage ,HttpServletRequest request ,HttpServletResponse response){");  
    568.         buffer.append(ENTER);  
    569.         buffer.append("         List<"+className+"> list = "+className+"Service.list(simplePage, "+objectName+");");  
    570.         buffer.append(ENTER);  
    571.         buffer.append("      request.setAttribute(""+objectName+"", object);");  
    572.         buffer.append(ENTER);  
    573.         buffer.append("      request.setAttribute("page", simplePage);");  
    574.         buffer.append(ENTER);  
    575.         buffer.append("      request.setAttribute("list", list);");  
    576.         buffer.append(ENTER);  
    577.         buffer.append("      return ""+BASE_PATH+"list";");  
    578.         buffer.append(ENTER);  
    579.         buffer.append("   }");  
    580.           
    581.         buffer.append(ENTER);  
    582.         buffer.append("}");  
    583.         buffer.append(ENTER);  
    584.         FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\.""/") + "/controller/" + className + "Controller.java", buffer.toString());  
    585.       
    586.           
    587.     }  
    588.       
    589.       
    590.     /*** 
    591.      * 创建JSP页面. 
    592.      * 以bootstrap3.x为主. 
    593.      * @param table 
    594.      */  
    595.     public void createJspView(String table)throws Exception{  
    596.   
    597.         String tableConstantName = getTableConstantName(table);  
    598.           
    599.         String className = getClassName(tableConstantName);//获取类名  
    600.         //通过 org.apache.commons.lang3.StringUtils的uncapitalize方法把类名第一个字母转换成小写  
    601.         String objectName = StringUtils.uncapitalize(className);  
    602.           
    603.         StringBuilder buffer = new StringBuilder();  
    604.            
    605.         buffer.append(" <%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>").append(ENTER);  
    606.         //这个就标注一下,这个taglib.jsp文件是JSTL的EL表达式,Spring 标签,自定义标签,等的文件。  
    607.         buffer.append("  <%@ include file="/WEB-INF/views/include/taglib.jsp"%>").append(ENTER);  
    608.         buffer.append(" <!DOCTYPE htm>").append(ENTER);  
    609.         buffer.append(" <html>").append(ENTER);  
    610.         buffer.append(" <head>").append(ENTER);  
    611.         //添加一个插件公共的文件,这个我就不一一备注  
    612.         buffer.append("  <%@ include file="/WEB-INF/views/include/meta.jsp"%>").append(ENTER);  
    613.         buffer.append("  <%@ include file="/WEB-INF/views/include/include.jsp"%>").append(ENTER);  
    614.         buffer.append(" <title></title>").append(ENTER);  
    615.         /**=======================添加style===Begin====================**/  
    616.         buffer.append(" <style>").append(ENTER);  
    617.         buffer.append("     .breadcrumb{").append(ENTER);  
    618.         buffer.append("         background-color: #fff;").append(ENTER);  
    619.         buffer.append("     }").append(ENTER);  
    620.         buffer.append("     .form-search{").append(ENTER);  
    621.         buffer.append("         background-color: #fff;").append(ENTER);  
    622.         buffer.append(" }").append(ENTER);  
    623.         buffer.append(" .form-search1{").append(ENTER);  
    624.         buffer.append("         padding: 8px 15px;").append(ENTER);  
    625.         buffer.append("         background-color: #f5f5f5;").append(ENTER);  
    626.         buffer.append("     }").append(ENTER);  
    627.         buffer.append(" </style>").append(ENTER);  
    628.         buffer.append(" </head>").append(ENTER);  
    629.         /**=======================添加style===End====================**/  
    630.           
    631.         buffer.append("<body>").append(ENTER);  
    632.         buffer.append("<ul class="nav nav-tabs">").append(ENTER);  
    633.         buffer.append( "<li class="active"><a href="${basePath}"+StringUtils.lowerCase(className)+"/list">"+className+"列表</a></li>").append(ENTER);  
    634.         buffer.append("</ul>").append(ENTER);  
    635.         buffer.append( " <form:form id="searchForm" modelAttribute=""+className+"" action="${basePath}"+StringUtils.lowerCase(className)+"/list" method="post" class="breadcrumb form-search form-inline">").append(ENTER);  
    636.         buffer.append("  <div style="margin-bottom: 20px;" class="form-search1">").append(ENTER);  
    637.           
    638.         //这里可以判断数据库的字段的类型做变量弄处理条件查询.  
    639.            
    640.         for (Map<String, Object> col : getCols(table)) {  
    641.                
    642.             //判断如果是数据库表的字段是DateTime类型的就设值My97DatePicker插件上,方便大家使用.  
    643.             if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {  
    644.                 buffer.append("<input id=""+col.get(NAME).toString()+"" name=""+col.get(NAME).toString()+"" type="text" readonly="readonly" maxlength="20" class="Wdate"").append(ENTER);  
    645.                 //在这里用了$是为了查询的时候保留值.  
    646.                 buffer.append(" value="<fmt:formatDate value="${"+className+"."+col.get(NAME).toString()+"}" pattern="yyyy-MM-dd HH:mm:ss"/>"").append(ENTER);  
    647.                 buffer.append(" onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>").append(ENTER);  
    648.             } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {  
    649.                 //form:input是spring架构的input标签path必须要等于实体类要有的属性.否则会报错.placeholder是html5有的占位符的属性,  
    650.                 //htmlEscape也是spring的有属性.在这个jar下面,因为我这个工程是用maven搭建的,所有拷贝的时候,拷贝的时候它带上路径.方便大家伙找jar,而且我在这的spring是用3.x  
    651.                 //C:Usersliangjilong.m2 epositoryorgspringframeworkorg.springframework.web.servlet3.1.1.RELEASEorg.springframework.web.servlet-3.1.1.RELEASE.jar  
    652.                 //org.springframework.web.servlet-3.1.1.RELEASE.jar这个文件下面有一个spring-from.tld文件,可以找到path,htmlEscape等属性.  
    653.                 buffer.append("   <label>"+col.get(NAME).toString()+" :</label><form:input path=""+col.get(NAME).toString()+"" htmlEscape="false" maxlength="50" class="input-medium form-control" placeholder=""+col.get(NAME).toString()+""/>").append(ENTER);  
    654.             }else{  
    655.                 buffer.append("   <label>"+col.get(NAME).toString()+" :</label><form:input path=""+col.get(NAME).toString()+"" htmlEscape="false" maxlength="50" class="input-medium form-control" placeholder=""+col.get(NAME).toString()+""/>").append(ENTER);  
    656.             }  
    657.             buffer.append(ENTER);  
    658.         }  
    659.         //btn btn-info这个样式用过bootstrap的人都知道这个是.  
    660.         buffer.append("    &nbsp;<input id="btnSubmit" class="btn btn-info" type="submit" value="查询"/>").append(ENTER);  
    661.         buffer.append("  </div>").append(ENTER);  
    662.           
    663.         buffer.append("<table id="contentTable" class="table table-striped table-bordered table-hover">").append(ENTER);  
    664.         buffer.append("<thead>").append(ENTER);//thead标签End  
    665.         buffer.append("<tr>").append(ENTER);//tr标签End  
    666.         /*******遍历列表的th的列*****/  
    667.         for (Map<String, Object> col : getTableRemarks(table)) {  
    668.              for (String k : col.keySet()){    
    669.                 String colName = col.get(k).toString();  
    670.                 buffer.append("<th>").append(colName).append("</th>");  
    671.                 buffer.append(ENTER);  
    672.               }    
    673.         }  
    674.         buffer.append("<th>操作</th> ");  
    675.         buffer.append(ENTER);  
    676.           
    677.         buffer.append("</tr>").append(ENTER);  
    678.         buffer.append("</thead>").append(ENTER);  
    679.           
    680.         buffer.append("<tbody>").append(ENTER);  
    681.           
    682.         /*******遍历列表的td的列*****/  
    683.         buffer.append("   <c:forEach items="${list}" var=""+objectName+"" varStatus="row">").append(ENTER);  
    684.         buffer.append("     <tr>").append(ENTER);  
    685.         buffer.append("     <td>${row.index+1 }</td>").append(ENTER);  
    686.           
    687.         for (Map<String, Object> col : getCols(table)) {  
    688.             buffer.append("         <td>");  
    689.             if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {  
    690.                 //如果是Date类型就转换用EL表达式格式化fmt:formatDate  
    691.                 buffer.append("<fmt:formatDate value="${"+objectName+"."+col.get(NAME).toString()+"}"  type="date" dateStyle="long"/>");  
    692.             } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {  
    693.                 buffer.append(" ${"+objectName+"."+col.get(NAME).toString()+"}" );  
    694.             }else{  
    695.                 buffer.append(" ${"+objectName+"."+col.get(NAME).toString()+"}" );  
    696.             }  
    697.             buffer.append("</td>");  
    698.             buffer.append(ENTER);  
    699.         }  
    700.           
    701.         buffer.append("    </tr>").append(ENTER);  
    702.         buffer.append("   </c:forEach>").append(ENTER);  
    703.         buffer.append("</tbody>").append(ENTER);//tbody标签结束.  
    704.           
    705.         buffer.append("</table>").append(ENTER);  
    706.         //这个是pagination.jsp是分页文件.  
    707.         buffer.append("<%@ include file="/WEB-INF/views/include/pagination.jsp"%>").append(ENTER);  
    708.         buffer.append("</form:form>").append(ENTER);//form:form标签结束.  
    709.         buffer.append("</body>").append(ENTER);//body标签结束.  
    710.         buffer.append("</html>").append(ENTER);//html标签结束.  
    711.         buffer.append(ENTER);  
    712.         buffer.append(ENTER);  
    713.         FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\.""/") + "/jsp/" + className + ".jsp", buffer.toString());  
    714.           
    715.     }  
    716.       
    717.       
    718.     /*** 
    719.      * 创建表的类定义常量 
    720.      * @param tables 
    721.      */  
    722.     public void createTableClass(List<String> tables) {  
    723.         StringBuilder buffer = new StringBuilder();  
    724.         buffer.append("package " + ROOT_PACKAGE + ".domain;");  
    725.         buffer.append(ENTER);  
    726.         buffer.append(ENTER);  
    727.         buffer.append("/**  * @Created:" + NOW_DATE + "  * @Author " + AUTHOR + " ");  
    728.         buffer.append(" * @Version:").append(Version).append(ENTER);  
    729.         buffer.append(" * @Email:").append(myEmail).append(" */");  
    730.         buffer.append(ENTER);  
    731.         buffer.append("public interface Table {");  
    732.         buffer.append(ENTER);  
    733.         for (String table : tables) {  
    734.             buffer.append(TAB);  
    735.             buffer.append("String " + getTableConstantName(table) + " = "" + table.toUpperCase() + "";");  
    736.             buffer.append(ENTER);  
    737.         }  
    738.         buffer.append(ENTER);  
    739.         buffer.append("}");  
    740.         buffer.append(ENTER);  
    741.         FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\.""/") + "/domain/Table.java", buffer.toString());  
    742.     }  
    743.   
    744.     /*** 
    745.      * 获取数据库表名 
    746.      * @return 
    747.      * @throws Exception 
    748.      */  
    749.     public List<String> getTables() throws Exception {  
    750.         List<Object> params = new ArrayList<Object>();  
    751.         //System.out.println("==========="+DB_NAME);  
    752.         //params.add(DB_NAME);  
    753.         String dbname=DB_NAME;  
    754.         params.add(dbname);  
    755.           
    756.         ResultSet rs = DBHelperUtils.query("select table_name from information_schema.tables where table_schema = ? order by table_name", params);  
    757.         List<String> tables = new ArrayList<String>();  
    758.         while (rs.next()) {  
    759.             tables.add(rs.getString(1));          
    760.         }  
    761.         return tables;  
    762.     }  
    763.       
    764.     /*** 
    765.      * 列名 类型 => 说明 
    766.      * TABLE_CAT String => 表 catalog 
    767.      * TABLE_SCHEM String => 表 schema 
    768.      * TABLE_NAME String => 表名 
    769.      * TABLE_TYPE String => 表类型 
    770.      * REMARKS String => 表注释 
    771.      * 获取表的列 
    772.      * @param table 
    773.      * @return 
    774.      * @throws Exception 
    775.      */  
    776.     private List<Map<String, Object>> getCols(String table) throws Exception {  
    777.          List<Map<String, Object>> cols = new ArrayList<Map<String,Object>>();  
    778.          ResultSetMetaData md = DBHelperUtils.query("select * from " + table + " where 1 = 2"null).getMetaData();  
    779.            
    780.          for (int i = 1; i <= md.getColumnCount(); i++) {  
    781.              Map<String, Object> col = new HashMap<String, Object>();  
    782.              cols.add(col);  
    783.              col.put(NAME, md.getColumnName(i));  
    784.              col.put(CLASS, md.getColumnClassName(i));  
    785.              col.put(SIZE, md.getColumnDisplaySize(i));  
    786.              col.put(REMARKS, md.getColumnName(i));  
    787.         /*  System.out.println("1"+ md.getCatalogName(i)); 
    788.             System.out.println("2"+ md.getColumnClassName(i)); 
    789.             System.out.println("3"+ md.getColumnDisplaySize(i)); 
    790.             System.out.println("4"+ md.getColumnType(i)); 
    791.             System.out.println("5"+ md.getSchemaName(i)); 
    792.             System.out.println("6"+ md.getPrecision(i)); 
    793.             System.out.println("7"+ md.getScale(i));*/  
    794.                
    795.              String _type = null;  
    796.              String type = md.getColumnTypeName(i);  
    797.              if(type.equals("INT")) {  
    798.                  _type = "INTEGER";  
    799.              } else if(type.equals("DATETIME")) {  
    800.                  _type = "TIMESTAMP";  
    801.              } else {  
    802.                  _type = type;  
    803.              }  
    804.              col.put(TYPE, _type);  
    805.         }  
    806.         return cols;  
    807.     }  
    808.    
    809.       
    810.     /** 
    811.      * 获取所有表 
    812.      * @param conn 
    813.      * @throws SQLException 
    814.      */  
    815.     public static   List<Map<String, Object>> getAllTable() throws SQLException {  
    816.         /** 
    817.          * 定义一个Lis 
    818.          */  
    819.         List<Map<String, Object>> cols = new ArrayList<Map<String,Object>>();  
    820.         DatabaseMetaData metaData = DBHelperUtils.getInstance().getDatabaseMetaData();  
    821.   
    822.         //这个是获取所有表.  
    823.         ResultSet rs = metaData.getTables(null"%""%"new String[] {"TABLE"});  
    824.   
    825.         while (rs.next()) {  
    826.             String tableName = rs.getString("TABLE_NAME");////这个是获取表名  
    827.   
    828.             if(tableName!=null){  
    829.                 Map<String, Object> col = new HashMap<String, Object>();  
    830.                 // rs =getConnection.getMetaData().getColumns(null, getXMLConfig.getSchema(),tableName.toUpperCase(), "%");  
    831.                 //其他数据库不需要这个方法的,直接传null,这个是oracle和db2这么用  
    832.                   
    833.                 ResultSet rs1 = metaData.getColumns(null"%", tableName, "%");  
    834.                   
    835.                 while(rs1.next()){  
    836.                     String COLUMN_NAME = rs1.getString("COLUMN_NAME");  
    837.                     String REMARKS = rs1.getString("REMARKS");  
    838.                     //先判断备注是否为空,不为空就取表的字段的注释说明,否则的话就去字段列名  
    839.                     if(REMARKS==null||REMARKS==""){  
    840.                         col.put(COLUMN_NAME, COLUMN_NAME);  
    841.                     }else{  
    842.                         col.put(REMARKS, REMARKS);  
    843.                     }  
    844.                     cols.add(col);  
    845.                 }  
    846.             }  
    847.         }  
    848.         return cols;  
    849.     }  
    850.       
    851.     /*** 
    852.      * 获取列的备注 
    853.      * @param table 
    854.      * @return 
    855.      * @throws SQLException 
    856.      */  
    857.     public static List<Map<String, Object>> getTableRemarks(String table) throws SQLException {  
    858.           
    859.         List<Map<String, Object>> cols = new ArrayList<Map<String,Object>>();  
    860.            
    861.         Connection conn=DBHelperUtils.getInstance().getConnection();  
    862.         DatabaseMetaData metaData = conn.getMetaData();  
    863.   
    864.         ResultSet rs = metaData.getTables(null"%""%"new String[] {"TABLE"});  
    865.   
    866.         while (rs.next()) {  
    867.               
    868.             String tableName = rs.getString("TABLE_NAME");  
    869.             //传进来的表名和查询出来的表名作对比,并且是忽略大小写  
    870.             if(tableName!=null){  
    871.                 if(table.equalsIgnoreCase(tableName)){  
    872.                     Map<String, Object> col = new HashMap<String, Object>();  
    873.                     //Map<String, Object> col = new HashTable<String, Object>();  
    874.                     ResultSet rs1 = metaData.getColumns(null"%", tableName, "%");  
    875.                    while(rs1.next()){  
    876.                         String COLUMN_NAME = rs1.getString("COLUMN_NAME");  
    877.                         String REMARKS = rs1.getString("REMARKS");  
    878.                           
    879.                         //先判断备注是否为空,不为空就取表的字段的注释说明,否则的话就去字段列名  
    880.                          
    881.                         if(REMARKS==null||REMARKS==""){  
    882.                             col.put(COLUMN_NAME, COLUMN_NAME);  
    883.                         }else{  
    884.                             col.put(REMARKS, REMARKS);  
    885.                         }  
    886.                         //去掉重复的数据  
    887.                         col = removeRepeatData();  
    888.                         cols.add(col);  
    889.                    }  
    890.                    break;  
    891.                 }  
    892.             }  
    893.         }  
    894.         return cols;  
    895.     }  
    896.        
    897.     /** 
    898.      * 获取表的主键. 
    899.      * @param tableName 
    900.      */  
    901.     public static String getTablePrimaryKeys(String tableName)throws Exception{  
    902.         DatabaseMetaData metaData = DBHelperUtils.getInstance().getDatabaseMetaData();  
    903.         ResultSet pkRSet = metaData.getPrimaryKeys(nullnull, tableName);   
    904.           
    905.         String primaryKey = "";  
    906.         if(pkRSet.next() ) {   
    907.             //把这个列的名称获取出来  
    908.               primaryKey = pkRSet.getString("PK_NAME");//PK_NAME/COLUMN_NAME  
    909.               primaryKey=(primaryKey==null?"":primaryKey);   
    910.                 
    911.               System.out.println(primaryKey);  
    912.         }   
    913.         return primaryKey;  
    914.     }  
    915.       
    916.     /** 
    917.      * 获取表的主键和外键包括外键表的名 
    918.      * @param tableName 
    919.      */  
    920.     public static String[] getTablePrimaryKeyForeignKey(String tableName)throws Exception{  
    921.         DatabaseMetaData metaData = DBHelperUtils.getInstance().getDatabaseMetaData();  
    922.         ResultSet fkSet = metaData.getPrimaryKeys(nullnull, tableName);   
    923.         String pkColumnName="",fkColumnName="",pkTablenName="";  
    924.         String [] paramsKey= new String[3];  
    925.           
    926.         while(fkSet.next()){  
    927.              pkColumnName = fkSet.getString("PK_NAME");//主键在网查到的有可能是PKCOLUMN_NAME  
    928.              fkColumnName = fkSet.getString("FK_NAME");//外键网查到的有可能是PKCOLUMN_NAME  
    929.              pkTablenName = fkSet.getString("PKTABLE_NAME");//主键表名  
    930.              //System.out.println(pkColumnName+fkColumnName+pkTablenName);  
    931.              pkColumnName=(pkColumnName==null?"":pkColumnName);  
    932.              fkColumnName=(fkColumnName==null?"":fkColumnName);  
    933.              pkTablenName=(pkTablenName==null?"":pkTablenName);  
    934.              paramsKey[0]=fkColumnName;  
    935.              paramsKey[1]=fkColumnName;  
    936.              paramsKey[2]=pkTablenName;  
    937.         }    
    938.            
    939.         return paramsKey;  
    940.     }  
    941.   
    942.     /*** 
    943.      * 去掉重复的数据 
    944.      * @return 
    945.      */  
    946.     private static Map<String, Object> removeRepeatData() {  
    947.         Map<String, Object> col = new HashMap<String, Object>();  
    948.         Set<String> keySet = col.keySet();  
    949.         for (String str : keySet) {  
    950.             col.put(str, str);  
    951.         }  
    952.         return col;  
    953.     }  
    954.       
    955.       
    956.     /*** 
    957.      * 获取表的常量名,一般是在数据库建表的时候,写的注释.. 
    958.      * @param table 
    959.      * @return 
    960.      */  
    961.     private String getTableConstantName(String table) {  
    962.         String tableConstantName = table.toUpperCase();  
    963.         for (String item : IGNORE_TABLE_PREFIX) {  
    964.             tableConstantName = tableConstantName.replaceAll("^" + item.toUpperCase(), "");  
    965.         }  
    966.         return tableConstantName;  
    967.     }  
    968.   
    969.     /*** 
    970.      * 获取类的名 
    971.      * @param name 
    972.      * @return 
    973.      */  
    974.     private String getClassName(String name) {  
    975.         String[] names = name.split("_");  
    976.         StringBuilder sb = new StringBuilder();  
    977.         for (String n : names) {  
    978.             if(n.length() == 0) {  
    979.                 sb.append("_");  
    980.             } else {  
    981.                 sb.append(n.substring(01).toUpperCase());  
    982.                 if(n.length() > 1) {  
    983.                     sb.append(n.substring(1).toLowerCase());  
    984.                 }  
    985.             }  
    986.         }  
    987.         return sb.toString();  
    988.     }  
    989.   
    990.     /** 
    991.      * 获取字段名 
    992.      * @param name 
    993.      * @return 
    994.      */  
    995.     private String getFieldName(String name) {  
    996.         String _name = getClassName(name);  
    997.         return _name.substring(01).toLowerCase() + _name.substring(1);  
    998.     }  
    999.   
    1000.   
    1001.     /** 
    1002.      * 转换成泛型Map 
    1003.      * @param limit 
    1004.      * @param rs 
    1005.      * @return 
    1006.      * @throws SQLException 
    1007.      */  
    1008.     public static List<Map> toListMap(int limit, ResultSet rs)throws SQLException {  
    1009.         ResultSetMetaData rsmd = rs.getMetaData();  
    1010.         int count = 0;  
    1011.         List list = new ArrayList();  
    1012.         while (rs.next()) {  
    1013.             Map row = new HashMap();  
    1014.             for (int i = 1; i <= rsmd.getColumnCount(); i++) {  
    1015.                 row.put(rsmd.getColumnName(i), rs.getObject(i));  
    1016.             }  
    1017.             list.add(row);  
    1018.             count++;  
    1019.             if (count >= limit) {  
    1020.                 break;  
    1021.             }  
    1022.         }  
    1023.         return list;  
    1024.      }  
    1025.       
    1026.     /*** 
    1027.      * 获取查询list 
    1028.      * @param conn 
    1029.      * @param sql 
    1030.      * @param limit 
    1031.      * @return 
    1032.      * @throws SQLException 
    1033.      */  
    1034.     public static List<Map> queryForList(Connection conn, String sql, int limit)throws SQLException {  
    1035.         PreparedStatement ps = conn.prepareStatement(sql.trim());  
    1036.         ps.setMaxRows(limit);  
    1037.         ps.setFetchDirection(1000);  
    1038.         ResultSet rs = ps.executeQuery();  
    1039.         return toListMap(limit, rs);  
    1040.     }  
    1041.     /*** 
    1042.      * 获取查询list 
    1043.      * @param conn 
    1044.      * @param sql 
    1045.      * @param limit 
    1046.      * @return 
    1047.      * @throws SQLException 
    1048.      */  
    1049.     public static List<Map> queryForList(String sql, int limit) throws SQLException {  
    1050.         Connection conn = DBHelperUtils.getConnection();  
    1051.         return queryForList(conn, sql, limit);  
    1052.     }  
    1053.       
    1054.       
    1055.     /*** 
    1056.      * 生成所有Entity,Dao,Service,Controller,JSP 代码 
    1057.      * @throws Exception 
    1058.      */  
    1059.     public void createAllCodeGenerator()throws Exception{  
    1060.         List<String> tables = getTables();  
    1061.         for (String table : tables) {  
    1062.             createEntityClass(table);//this is method create Entity  
    1063.             createDaoClass(table);//this is method create  Dao Interface  
    1064.             createDaoImplClass(table);//this is method create Dao implement  
    1065.             createServiceClass(table);//this is method create Service Interface  
    1066.             createServiceImplClass(table);//this is method create Service implement  
    1067.             createControllerClass(table);//this is method create Controller  
    1068.             createJspView(table);//this is method JspView  
    1069.         }  
    1070.          createTableClass(tables);  
    1071.           
    1072.     }  
    1073.       
    1074.       
    1075.     public static void main(String[] args)throws Exception {  
    1076.         String sql="select * from SYS_MENU ";  
    1077.         //List<Map> queryForList = queryForList(sql, 1000);  
    1078.         /*for(Map m:queryForList){ 
    1079.             System.out.println("======"+m); 
    1080.         }*/  
    1081.           
    1082.         String tableName = "SYS_MENU";//表名  
    1083.        
    1084.       /*    List<Map<String, Object>> tableRemarks = getTableRemarks(tableName); 
    1085.         int i=0; 
    1086.         for (Map<String, Object> col : getTableRemarks(tableName)) { 
    1087.             Set<String> keySet = col.keySet(); 
    1088.             for (Object str : keySet) { 
    1089.                 //System.out.println(str); 
    1090.             } 
    1091.         } 
    1092.         */  
    1093.         //getTablePrimaryKeys("test");  
    1094.           
    1095.         //new CodeGenerator().createJspView("sup_email");  
    1096.         new CodeGenerator().createEntityClass("test");  
    1097.         //new CodeGenerator().getTablePrimaryKeyForeignKey("test");  
    1098.         //String myId="My_id";  
    1099.          //boolean endsWith = myId.toString().toUpperCase().endsWith("_ID");  
    1100.         //if(col.get(NAME).toString().equalsIgnoreCase("ID") || col.get(NAME).toString().toUpperCase().endsWith("_ID"))  
    1101.         //if(endsWith){  
    1102.             //System.out.println(11111);  
    1103.         //}  
    1104.           
    1105.         //createAllCodeGenerator();  
    1106.           
    1107.     }  
    1108.   
    1109. }  

    Java代码  收藏代码
    1. package com.flong.codegenerator;  
    2.   
    3. import java.sql.Connection;  
    4. import java.sql.DatabaseMetaData;  
    5. import java.sql.DriverManager;  
    6. import java.sql.PreparedStatement;  
    7. import java.sql.ResultSet;  
    8. import java.sql.SQLException;  
    9. import java.util.List;  
    10. /*** 
    11.  *@Author:liangjilong 
    12.  *@Date:2015年12月5日下午12:25:12 
    13.  *@Email:jilongliang@sina.com 
    14.  *@Version:1.0 
    15.  *@CopyRight(c)Flong Intergrity Ltd. 
    16.  */  
    17. @SuppressWarnings("all")  
    18. public class DBHelperUtils {  
    19.     private static final Connection conn;  
    20.     private static final String driverClass = PropertiesHelper.getValueByKey("jdbc.driver");  
    21.     private static final String connectionUrl = PropertiesHelper.getValueByKey("jdbc.url");  
    22.     private static final String username = PropertiesHelper.getValueByKey("jdbc.username");  
    23.     private static final String password = PropertiesHelper.getValueByKey("jdbc.password");  
    24.       
    25.     private static DBHelperUtils instance = null;  
    26.     /** 
    27.      * 定义代码块. 
    28.      */  
    29.     static {  
    30.         try {  
    31.             Class.forName(driverClass);  
    32.             conn = DriverManager.getConnection(connectionUrl, username, password);  
    33.         } catch (Exception e) {  
    34.             throw new RuntimeException(e);  
    35.         }  
    36.     }  
    37.   
    38.     /**建立单例模式 
    39.      * Single 
    40.      * @return 
    41.      */  
    42.     public static DBHelperUtils getInstance() {  
    43.         if (instance == null) {  
    44.             synchronized (DBHelperUtils.class) {  
    45.                 instance = new DBHelperUtils();  
    46.             }  
    47.         }  
    48.         return instance;  
    49.     }  
    50.       
    51.       
    52.     /** 
    53.      * 查询数据 
    54.      * @param sql 
    55.      * @param params 
    56.      * @return 
    57.      */  
    58.     public static ResultSet query(String sql, List<Object> params) {  
    59.         System.out.println("sql: " + sql);  
    60.         //System.out.println("params: " + params);  
    61.         try {  
    62.             PreparedStatement psmt = conn.prepareStatement(sql);  
    63.             if(params != null) {  
    64.                 for (int i = 0; i < params.size(); i++) {  
    65.                     psmt.setObject(i+1, params.get(i));  
    66.                 }  
    67.             }     
    68.             return psmt.executeQuery();  
    69.         } catch (SQLException e) {  
    70.             throw new RuntimeException(e);  
    71.         }  
    72.     }  
    73.   
    74.     /*** 
    75.      * 更新 
    76.      * @param sql 
    77.      * @param params 
    78.      */  
    79.     public static void update(String sql, List<Object> params) {  
    80.         System.out.println("sql: " + sql);  
    81.         //System.out.println("params: " + params);  
    82.         try {  
    83.             PreparedStatement psmt = conn.prepareStatement(sql);  
    84.             if(params != null) {  
    85.                 for (int i = 0; i < params.size(); i++) {  
    86.                     psmt.setObject(i+1, params.get(i));  
    87.                 }  
    88.             }     
    89.             psmt.executeUpdate();  
    90.         } catch (SQLException e) {  
    91.             throw new RuntimeException(e);  
    92.         }  
    93.     }  
    94.       
    95.     /** 
    96.      * 获取链接 
    97.      * @return 
    98.      */  
    99.     public static Connection getConnection(){  
    100.         try {  
    101.             Class.forName(driverClass);  
    102.             return DriverManager.getConnection(connectionUrl, username, password);  
    103.         } catch (Exception e) {  
    104.             e.printStackTrace();  
    105.         }    
    106.         return null;  
    107.     }  
    108.       
    109.       
    110.       
    111.     /** 
    112.      * 获取数据DatabaseMetaData对象 
    113.      * @return 
    114.      */  
    115.     public DatabaseMetaData  getDatabaseMetaData(){  
    116.           
    117.         try {  
    118.             return getInstance().getConnection().getMetaData();  
    119.         } catch (SQLException e) {  
    120.             e.printStackTrace();  
    121.         }  
    122.         return null;  
    123.     }  
    124.       
    125.       
    126.      /**  
    127.      * 获得数据库的一些相关信息  
    128.      */    
    129.     public void getDataBaseInformations() {    
    130.         try {               
    131.             System.out.println("数据库已知的用户: "+ getDatabaseMetaData().getUserName());      
    132.             System.out.println("数据库的系统函数的逗号分隔列表: "+ getDatabaseMetaData().getSystemFunctions());      
    133.             System.out.println("数据库的时间和日期函数的逗号分隔列表: "+ getDatabaseMetaData().getTimeDateFunctions());      
    134.             System.out.println("数据库的字符串函数的逗号分隔列表: "+ getDatabaseMetaData().getStringFunctions());      
    135.             System.out.println("数据库供应商用于 'schema' 的首选术语: "+ getDatabaseMetaData().getSchemaTerm());      
    136.             System.out.println("数据库URL: " + getDatabaseMetaData().getURL());      
    137.             System.out.println("是否允许只读:" + getDatabaseMetaData().isReadOnly());      
    138.             System.out.println("数据库的产品名称:" + getDatabaseMetaData().getDatabaseProductName());      
    139.             System.out.println("数据库的版本:" + getDatabaseMetaData().getDatabaseProductVersion());      
    140.             System.out.println("驱动程序的名称:" + getDatabaseMetaData().getDriverName());      
    141.             System.out.println("驱动程序的版本:" + getDatabaseMetaData().getDriverVersion());     
    142.     
    143.             System.out.println();      
    144.             System.out.println("数据库中使用的表类型");      
    145.             ResultSet rs = getDatabaseMetaData().getTableTypes();      
    146.             while (rs.next()) {      
    147.                 System.out.println(rs.getString(1));      
    148.             }      
    149.             rs.close();                  
    150.             System.out.println();    
    151.         } catch (SQLException e) {    
    152.             e.printStackTrace();    
    153.         }    
    154.     }    
    155.       
    156.     /**  
    157.      * 获得该用户下面的所有表  
    158.      */    
    159.     public void getAllTableList(String schemaName) {    
    160.         try {    
    161.             // table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".    
    162.             String[] types = { "TABLE" };    
    163.             ResultSet rs = getDatabaseMetaData().getTables(null, schemaName, "%", types);    
    164.             while (rs.next()) {    
    165.                 String tableName = rs.getString("TABLE_NAME");  //表名    
    166.                 String tableType = rs.getString("TABLE_TYPE");  //表类型    
    167.                 String remarks = rs.getString("REMARKS");       //表备注    
    168.                 System.out.println(tableName + "-" + tableType + "-" + remarks);    
    169.             }    
    170.         } catch (SQLException e) {    
    171.             e.printStackTrace();    
    172.         }    
    173.     }    
    174.       
    175.     /**  
    176.      * 获得该用户下面的所有视图  
    177.      */    
    178.     public void getAllViewList(String schemaName) {    
    179.          try{      
    180.              String[] types = { "VIEW" };                   
    181.              ResultSet rs = getDatabaseMetaData().getTables(null, schemaName, "%", types);    
    182.              while (rs.next()){    
    183.                  String viewName = rs.getString("TABLE_NAME"); //视图名    
    184.                  String viewType = rs.getString("TABLE_TYPE"); //视图类型    
    185.                  String remarks = rs.getString("REMARKS");      //视图备注    
    186.                  System.out.println(viewName + "-" + viewType + "-" + remarks);    
    187.              }    
    188.          } catch (SQLException e) {    
    189.              e.printStackTrace();    
    190.          }    
    191.     }    
    192.         
    193.      /**    
    194.      * 获得数据库中所有方案名称    
    195.      */      
    196.     public void getAllSchemas(){    
    197.         try{    
    198.             ResultSet rs = getDatabaseMetaData().getSchemas();     
    199.             while (rs.next()){       
    200.                 String tableSchem = rs.getString("TABLE_SCHEM");       
    201.                 System.out.println(tableSchem);       
    202.             }       
    203.         } catch (SQLException e){    
    204.             e.printStackTrace();       
    205.         }       
    206.     }       
    207.     
    208.     
    209.     /**  
    210.      * 获得表或视图中的所有列信息  
    211.      */    
    212.     public void getTableColumns(String schemaName, String tableName) {    
    213.              
    214.         try{       
    215.                     
    216.             ResultSet rs = getDatabaseMetaData().getColumns(null, schemaName, tableName, "%");                
    217.             while (rs.next()){    
    218.                     String tableCat = rs.getString("TABLE_CAT");//表目录(可能为空)                    
    219.                     String tableSchemaName = rs.getString("TABLE_SCHEM");//表的架构(可能为空)       
    220.                     String tableName_ = rs.getString("TABLE_NAME");//表名    
    221.                     String columnName = rs.getString("COLUMN_NAME");//列名    
    222.                     int dataType = rs.getInt("DATA_TYPE"); //对应的java.sql.Types类型       
    223.                     String dataTypeName = rs.getString("TYPE_NAME");//java.sql.Types类型   名称    
    224.                     int columnSize = rs.getInt("COLUMN_SIZE");//列大小    
    225.                     int decimalDigits = rs.getInt("DECIMAL_DIGITS");//小数位数    
    226.                     int numPrecRadix = rs.getInt("NUM_PREC_RADIX");//基数(通常是10或2)    
    227.                     int nullAble = rs.getInt("NULLABLE");//是否允许为null    
    228.                     String remarks = rs.getString("REMARKS");//列描述    
    229.                     String columnDef = rs.getString("COLUMN_DEF");//默认值    
    230.                     int sqlDataType = rs.getInt("SQL_DATA_TYPE");//sql数据类型    
    231.                     int sqlDatetimeSub = rs.getInt("SQL_DATETIME_SUB");   //SQL日期时间分?    
    232.                     int charOctetLength = rs.getInt("CHAR_OCTET_LENGTH");   //char类型的列中的最大字节数    
    233.                     int ordinalPosition = rs.getInt("ORDINAL_POSITION");  //表中列的索引(从1开始)    
    234.                         
    235.                     /**  
    236.                      * ISO规则用来确定某一列的为空性。  
    237.                      * 是---如果该参数可以包括空值;  
    238.                      * 无---如果参数不能包含空值  
    239.                      * 空字符串---如果参数为空性是未知的  
    240.                      */    
    241.                     String isNullAble = rs.getString("IS_NULLABLE");    
    242.                         
    243.                     /**  
    244.                      * 指示此列是否是自动递增  
    245.                      * 是---如果该列是自动递增  
    246.                      * 无---如果不是自动递增列  
    247.                      * 空字串---如果不能确定它是否  
    248.                      * 列是自动递增的参数是未知  
    249.                      */    
    250.                     String isAutoincrement = rs.getString("IS_AUTOINCREMENT");       
    251.                         
    252.                     System.out.println(tableCat + "-" + tableSchemaName + "-" + tableName_ + "-" + columnName + "-"      
    253.                             + dataType + "-" + dataTypeName + "-" + columnSize + "-" + decimalDigits + "-" + numPrecRadix       
    254.                             + "-" + nullAble + "-" + remarks + "-" + columnDef + "-" + sqlDataType + "-" + sqlDatetimeSub       
    255.                             + charOctetLength + "-" + ordinalPosition + "-" + isNullAble + "-" + isAutoincrement + "-");       
    256.                 }       
    257.             } catch (SQLException e){    
    258.                 e.printStackTrace();       
    259.             }    
    260.     }    
    261.     
    262.     
    263.     /**  
    264.      * 获得一个表的索引信息  
    265.      */    
    266.     public void getIndexInfo(String schemaName, String tableName) {    
    267.         try{    
    268.             ResultSet rs = getDatabaseMetaData().getIndexInfo(null, schemaName, tableName, truetrue);    
    269.             while (rs.next()){    
    270.                 boolean nonUnique = rs.getBoolean("NON_UNIQUE");//非唯一索引(Can index values be non-unique. false when TYPE is  tableIndexStatistic   )    
    271.                 String indexQualifier = rs.getString("INDEX_QUALIFIER");//索引目录(可能为空)    
    272.                 String indexName = rs.getString("INDEX_NAME");//索引的名称    
    273.                 short type = rs.getShort("TYPE");//索引类型    
    274.                 short ordinalPosition = rs.getShort("ORDINAL_POSITION");//在索引列顺序号    
    275.                 String columnName = rs.getString("COLUMN_NAME");//列名    
    276.                 String ascOrDesc = rs.getString("ASC_OR_DESC");//列排序顺序:升序还是降序    
    277.                 int cardinality = rs.getInt("CARDINALITY");   //基数    
    278.                 System.out.println(nonUnique + "-" + indexQualifier + "-" + indexName + "-" + type + "-" + ordinalPosition + "-" + columnName + "-" + ascOrDesc + "-" + cardinality);       
    279.             }       
    280.         } catch (SQLException e){    
    281.             e.printStackTrace();       
    282.         }     
    283.     }    
    284.     
    285.     
    286.     /**  
    287.      * 获得一个表的主键信息  
    288.      */    
    289.     public void getAllPrimaryKeys(String schemaName, String tableName) {    
    290.         try{    
    291.             ResultSet rs = getDatabaseMetaData().getPrimaryKeys(null, schemaName, tableName);    
    292.             while (rs.next()){    
    293.                 String columnName = rs.getString("COLUMN_NAME");//列名    
    294.                 short keySeq = rs.getShort("KEY_SEQ");//序列号(主键内值1表示第一列的主键,值2代表主键内的第二列)    
    295.                 String pkName = rs.getString("PK_NAME"); //主键名称      
    296.                 System.out.println(columnName + "-" + keySeq + "-" + pkName);       
    297.             }    
    298.         }catch (SQLException e){    
    299.             e.printStackTrace();    
    300.         }    
    301.     }    
    302.     
    303.     
    304.     /**  
    305.      * 获得一个表的外键信息  
    306.      */    
    307.     public void getAllExportedKeys(String schemaName, String tableName) {    
    308.             
    309.         try{    
    310.             ResultSet rs = getDatabaseMetaData().getExportedKeys(null, schemaName, tableName);    
    311.             while (rs.next()){    
    312.                 String pkTableCat = rs.getString("PKTABLE_CAT");//主键表的目录(可能为空)    
    313.                 String pkTableSchem = rs.getString("PKTABLE_SCHEM");//主键表的架构(可能为空)    
    314.                 String pkTableName = rs.getString("PKTABLE_NAME");//主键表名     
    315.                 String pkColumnName = rs.getString("PKCOLUMN_NAME");//主键列名      
    316.                 String fkTableCat = rs.getString("FKTABLE_CAT");//外键的表的目录(可能为空)出口(可能为null)    
    317.                 String fkTableSchem = rs.getString("FKTABLE_SCHEM");//外键表的架构(可能为空)出口(可能为空)    
    318.                 String fkTableName = rs.getString("FKTABLE_NAME");//外键表名    
    319.                 String fkColumnName = rs.getString("FKCOLUMN_NAME"); //外键列名                    
    320.                 short keySeq = rs.getShort("KEY_SEQ");//序列号(外键内值1表示第一列的外键,值2代表在第二列的外键)。    
    321.                     
    322.                 /**  
    323.                  * hat happens to foreign key when primary is updated:   
    324.                  * importedNoAction - do not allow update of primary key if it has been imported  
    325.                  * importedKeyCascade - change imported key to agree with primary key update   
    326.                  * importedKeySetNull - change imported key to NULL if its primary key has been updated  
    327.                  * importedKeySetDefault - change imported key to default values if its primary key has been updated  
    328.                  * importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)     
    329.                  */    
    330.                 short updateRule = rs.getShort("UPDATE_RULE");    
    331.                     
    332.                 /**  
    333.                  * What happens to the foreign key when primary is deleted.  
    334.                  * importedKeyNoAction - do not allow delete of primary key if it has been imported  
    335.                  * importedKeyCascade - delete rows that import a deleted key   
    336.                  * importedKeySetNull - change imported key to NULL if its primary key has been deleted   
    337.                  * importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)  
    338.                  * importedKeySetDefault - change imported key to default if its primary key has been deleted     
    339.                  */    
    340.                 short delRule = rs.getShort("DELETE_RULE");    
    341.                 String fkName = rs.getString("FK_NAME");//外键的名称(可能为空)    
    342.                 String pkName = rs.getString("PK_NAME");//主键的名称(可能为空)    
    343.                     
    344.                 /**  
    345.                  * can the evaluation of foreign key constraints be deferred until commit  
    346.                  * importedKeyInitiallyDeferred - see SQL92 for definition  
    347.                  * importedKeyInitiallyImmediate - see SQL92 for definition   
    348.                  * importedKeyNotDeferrable - see SQL92 for definition     
    349.                  */    
    350.                 short deferRability = rs.getShort("DEFERRABILITY");    
    351.                     
    352.                 System.out.println(pkTableCat + "-" + pkTableSchem + "-" + pkTableName + "-" + pkColumnName + "-"      
    353.                         + fkTableCat + "-" + fkTableSchem + "-" + fkTableName + "-" + fkColumnName + "-" + keySeq + "-"      
    354.                         + updateRule + "-" + delRule + "-" + fkName + "-" + pkName + "-" + deferRability);       
    355.             }    
    356.         } catch (SQLException e){    
    357.             e.printStackTrace();       
    358.         }    
    359.     }    
    360.     
    361.     
    362.     public void closeResource() {    
    363.         try {    
    364.             if (conn != null) {    
    365.                 conn.close();    
    366.             }    
    367.         } catch (SQLException e) {    
    368.             e.printStackTrace();    
    369.         }    
    370.     }    
    371.     
    372.       
    373.     public static void main(String[] args) throws Exception {  
    374.         DBHelperUtils metaData = new DBHelperUtils();    
    375.         metaData.getDataBaseInformations();    
    376.         metaData.getAllTableList(null);    
    377.         metaData.getAllViewList(null);    
    378.         metaData.getAllSchemas();    
    379.         metaData.getTableColumns(null"test");    
    380.         metaData.getIndexInfo(null"test");    
    381.         metaData.getAllPrimaryKeys(null"test");    
    382.         metaData.getAllExportedKeys(null"test");    
    383.     }  
    384.       
    385.   
    386. }  

     

    Java代码  收藏代码
    1. package com.flong.codegenerator;  
    2.   
    3. import java.io.File;  
    4. import java.io.FileWriter;  
    5.   
    6. public class FileUtils {  
    7.     /** 
    8.      * 把生成的文件都保存. 
    9.      * @param path 
    10.      * @param data 
    11.      */  
    12.     public static void save(String path, String data) {  
    13.         try {  
    14.             File file = new File(path);  
    15.             File dir = new File(path.substring(0, path.lastIndexOf("/")));  
    16.             if(!dir.exists()) {  
    17.                 dir.mkdirs();  
    18.             }  
    19.             FileWriter out = new FileWriter(file);  
    20.             out.write(data);  
    21.             out.flush();  
    22.             out.close();  
    23.         } catch (Exception e) {  
    24.             throw new RuntimeException(e);  
    25.         }  
    26.     }  
    27. }  

      

    Java代码  收藏代码
    1. package com.flong.codegenerator;  
    2.   
    3.   
    4. import java.util.HashMap;  
    5. import java.util.Map;  
    6. import java.util.Map.Entry;  
    7. import java.util.Properties;  
    8. /*** 
    9.  *@Author:liangjilong 
    10.  *@Date:2015年12月5日下午12:25:12 
    11.  *@Email:jilongliang@sina.com 
    12.  *@Version:1.0 
    13.  *@CopyRight(c)Flong Intergrity Ltd. 
    14.  *@Description:读取文properties 
    15.  */  
    16. public class PropertiesHelper {  
    17.   
    18.     private static final Map<String, String> properties = new HashMap<String, String>();  
    19.     static {  
    20.         try {  
    21.             Properties pps = new Properties();  
    22.             pps.load(PropertiesHelper.class.getClassLoader().getResourceAsStream("prop/DBSource.properties"));  
    23.             //处理重复的值.  
    24.             for (Entry<Object, Object> entry : pps.entrySet()) {  
    25.                 properties.put(entry.getKey().toString().trim(), entry.getValue().toString().trim());  
    26.             }  
    27.         } catch (Exception e) {  
    28.             throw new RuntimeException(e);  
    29.         }  
    30.     }  
    31.   
    32.     /** 
    33.      *通过key值去获取值. 
    34.      */  
    35.     public static String getValueByKey(String name) {  
    36.         return properties.get(name);  
    37.     }  
    38.   
    39. }  

     

    Java代码  收藏代码
    1. #mysql database setting  
    2. jdbc.driver=com.mysql.jdbc.Driver  
    3. jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8  
    4. jdbc.username=root  
    5. jdbc.password=root  

     

     

     

    其中源码在一个CodeGenerator.Java里面

     

    SQL生成器和代码生成器源代码下载地址 http://download.csdn.NET/detail/l_ji_l/9797834

        <ul style="display:none;">
          <li><a href="http://dl2.iteye.com/upload/attachment/0113/5679/94412eec-7542-3c74-9162-6d6c400ad45a.png" target="_blank"><img src="http://dl2.iteye.com/upload/attachment/0113/5679/94412eec-7542-3c74-9162-6d6c400ad45a-thumb.png" class="magplus" title="点击查看原始大小图片"></a></li>
          
          <li>大小: 43.1 KB</li>
        </ul>
      
    
      
        <ul>
          <li><a href="http://dl.iteye.com/topics/download/5556475d-eedc-3f93-8a81-f7dfb6d65235">codegenerator.zip</a> (15.8 KB)</li>
          
          <li>下载次数: 154</li>
        </ul>
      
    
    
      <ul>
        <li><a href="#" onclick="$$('div.attachments ul').invoke('show');$(this).up(1).hide();return false;">查看图片附件</a></li>
      </ul>
    
  • 相关阅读:
    错误:Char 26: fatal error: reference to non-static member function must be called
    【C++】去除字符串string中的空格(两头空格、所有空格)
    【C/C++】字符串string与字符数组char*的相互转换
    【C++】if-else编程陷阱
    【数据结构与算法】《剑指offer》学习笔记----第一章、第二章 基础知识(含1-15题)
    LeetCode运行报错: reference binding to null pointer of type 'value_type'
    【深度学习机配置】Dell服务站各组件型号记录
    【C++、二分法】LeetCode744. 寻找比目标字母大的最小字母
    Python视频抽帧成图片
    Windows10自带的录屏软件,十分强大
  • 原文地址:https://www.cnblogs.com/jpfss/p/8854940.html
Copyright © 2011-2022 走看看