- package com.flong.codegenerator;
- import java.sql.Connection;
- import java.sql.DatabaseMetaData;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.sql.Timestamp;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import org.apache.commons.lang3.StringUtils;
- /***
- *@Author:liangjilong
- *@Date:2015年12月5日下午12:25:12
- *@Email:jilongliang@sina.com
- *@Version:1.0
- *@CopyRight(c)Flong Intergrity Ltd.
- *@Desction:★★★★★★★★★★★★★★★代碼生成器實現思路★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
- *
- * ★★在快速開發的過程當中,爲了節省時間和成本不少人都會開發本身的代碼生成器,並且成爲程序員開發過程當中必不可少的神器.
- * ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
- * 第一種:先有數據庫表,而後經過jdbc連接數據庫再讀取表的字段等屬性出來生成Entity,Dao,Service,Controller,JSP等代碼
- * 這種必須是有數據庫和表的思想,經過程序去讀取數據庫表的屬性等信息,而後組織代碼經過文件流生成文件.
- *
- * ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
- * 第二種:已經設計好數據庫表文檔,把全部表的字段屬性配置到EXCEL或者CSV格式的文件經過JXL/POI技術去讀取文件的字段實現
- * Entity,Dao,Service,Controller,JSP,在過程當中會藉助Freemaker,Velocity去實現.三層和jsp,而後經過一下ORM(hibernate,
- * ibatis,myibatis等)技術逆向生成數據庫表.這種是無數據庫表的思想. 在生成java的代碼通常不建議建ORM映射主從表關係,經過
- * SQL去創建關係,爲啥?由於在一些大型的公司如:銀行,阿里巴巴,電信等公司,不少項目開發過程當中在數據庫表不多創建表關係的
- * 由於在些業務複雜的狀況下經過SQL和程序控制的解決方案比ORM映射關係方案佔優點.好比優化性能/維護/靈活性更加好等.
- * ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
- *
- * 此程序以MySQL爲主,未實現其餘數據庫.此程序能夠再優化的,爲了有些初學者,就不做太多的處理和優化.一些高手會編程更好的生
- * 成器,此程序只提供參考和學習,若有什麼問題,能夠多指出.共同窗習和進步.謝謝!~
- * ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
- */
- @SuppressWarnings("all")
- public class CodeGenerator {
- /*************************變量****Begin************************************/
- private static final String myEmail="jilongliang@sina.com";//Email
- private static final String Version="1.0";//版本
- private static final String Description=" ";//描述
- public static final String ENTER = "\n";//換行
- public static final String TAB = " ";//tab空格.
- public static final String NAME = "NAME";
- public static final String TABLE_CAT = "TABLE_CAT";//表 catalog
- public static final String TABLE_SCHEM = "TABLE_SCHEM";//表 schema
- public static final String TABLE_NAME = "TABLE_NAME";//表名
- public static final String TABLE_TYPE = "TABLE_TYPE";//表類型
- public static final String REMARKS = "REMARKS";//表註釋
- public static final String TYPE = "TYPE";//表的類型
- public static final String SIZE = "SIZE";//大小
- public static final String CLASS = "CLASS";//類別
- /*************************變量****End************************************/
- public static final String NOW_DATE = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
- /***************獲取數據庫的配置鏈接************/
- public static final String DB_NAME = PropertiesHelper.getValueByKey("jdbc.url").substring(
- PropertiesHelper.getValueByKey("jdbc.url").lastIndexOf("/")+1,
- PropertiesHelper.getValueByKey("jdbc.url").indexOf("?") == -1?
- PropertiesHelper.getValueByKey("jdbc.url").length():
- PropertiesHelper.getValueByKey("jdbc.url").indexOf("?"));
- //從配置獲取工程的報名路徑
- public static final String ROOT_PACKAGE = PropertiesHelper.getValueByKey("rootPackage");
- //獲取做者.
- public static final String AUTHOR = PropertiesHelper.getValueByKey("author");
- //忽略表的後綴.
- public static final List<String> IGNORE_TABLE_PREFIX = new ArrayList<String>();
- /*******定義代碼塊*******/
- static {
- String ignoreTablePrefix = PropertiesHelper.getValueByKey("ignoreTablePrefix");
- if(ignoreTablePrefix.length() > 0) {
- String[] ignoreTablePrefixs = ignoreTablePrefix.split("\\s*\\,\\s*");
- for (String elem : ignoreTablePrefixs) {
- IGNORE_TABLE_PREFIX.add(elem);
- }
- }
- }
- /***
- * 生成實體類的代碼
- * @param table
- * @throws Exception
- */
- public void createEntityClass(String table) throws Exception {
- String tableConstantName = getTableConstantName(table);
- String className = getClassName(tableConstantName);
- StringBuilder buffer = new StringBuilder();
- buffer.append("package " + ROOT_PACKAGE + ".entity;").append(ENTER);
- buffer.append("import java.util.Date;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.Entity;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.annotation.Column;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.annotation.Id;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.annotation.Relation;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.annotation.Table;").append(ENTER);
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("/**\n * @Created:" + NOW_DATE + "\n * @Author " + AUTHOR + "\n");
- buffer.append(" * @Version:").append(Version).append(ENTER);
- buffer.append(" * @Description:").append(className).append(ENTER);
- buffer.append(" * @Email:").append(myEmail).append("\n*/");
- buffer.append(ENTER);
- buffer.append("@Relation(" + className + ".TABLE)");
- buffer.append(ENTER);
- buffer.append("public class " + className + " extends Entity {");
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("/** 表名常量 */");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("public static final String TABLE = Table." + tableConstantName + ";");
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("/**");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append(" * 列名常量");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append(" */");
- buffer.append(ENTER);
- for (Map<String, Object> col : getCols(table)) {
- String colName = col.get(NAME).toString().toUpperCase();
- buffer.append(TAB);//生成字段變量
- buffer.append("public static final String COL_" + colName + " = \"" + colName + "\";//"+col.get(REMARKS));
- buffer.append(ENTER);
- }
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("/**");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append(" * 列屬性");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append(" */");
- String tablePrimaryKeys = getTablePrimaryKeys(table);//若是是主鍵
- //if(col.get(NAME).toString().equalsIgnoreCase("ID")) {
- if(tablePrimaryKeys!=null){
- buffer.append(ENTER+TAB);
- //若是主鍵不爲空的時候就給一個@Id註解.
- //若是是hibernate的能夠給其餘的註解,如@GeneratedValue(strategy = GenerationType.IDENTITY) @SequenceGenerator等
- //並要在包的下面頭部導入
- //import javax.persistence.Column;
- //import javax.persistence.Entity;
- //import javax.persistence.GeneratedValue;
- //import javax.persistence.GenerationType;
- //import javax.persistence.Id;
- //import javax.persistence.Table;
- buffer.append("@Id");
- //這裏不賦值給,由於下面這個for循環有一個.
- //sb.append("@Column(COL_" + tablePrimaryKeys + ")");
- }
- for (Map<String, Object> col : getCols(table)) {
- buffer.append(TAB);
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("@Column(COL_" + col.get(NAME).toString().toUpperCase() + ")");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("private ");
- //這行代碼的意思就是說,若是找到數據庫表的字段是爲ID的時候,或後綴有_ID的就認爲是主鍵,而且忽略大小寫就給一個Long
- //在實際過程當中應該判斷是它的字段是否是爲了PrimaryKey才設爲Long才適合.
- //if(col.get(NAME).toString().equalsIgnoreCase("ID") || col.get(NAME).toString().toUpperCase().endsWith("_ID")) {
- if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {
- buffer.append("Date");
- } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {
- buffer.append(col.get(CLASS));
- } else {
- buffer.append(Class.forName(col.get(CLASS).toString()).getSimpleName());
- }
- //sb.append(" " + getFieldName(col.get(NAME).toString()) + ";");
- buffer.append(" " + col.get(NAME).toString() + ";");
- buffer.append(ENTER);
- }
- buffer.append(ENTER);
- for (Map<String, Object> col : getCols(table)){
- buffer.append(TAB);
- buffer.append("public ");
- if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {
- buffer.append("Date");
- } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {
- buffer.append(col.get(CLASS));
- } else {
- buffer.append(Class.forName(col.get(CLASS).toString()).getSimpleName());
- }
- buffer.append(" ").append("get").append(col.get(NAME).toString().replaceFirst("\\b(\\w)|\\s(\\w)", col.get(NAME).toString().substring(0,1).toUpperCase()));
- buffer.append("() {");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append(TAB);
- buffer.append("return ").append(col.get(NAME).toString()).append(";");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("}");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("public void ").append("set").append(col.get(NAME).toString().replaceFirst("\\b(\\w)|\\s(\\w)", col.get(NAME).toString().substring(0,1).toUpperCase()));
- buffer.append("(");
- if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {
- buffer.append("Date");
- } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {
- buffer.append(col.get(CLASS));
- } else {
- buffer.append(Class.forName(col.get(CLASS).toString()).getSimpleName());
- }
- buffer.append(" ").append(col.get(NAME).toString());
- buffer.append(") {");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append(TAB);
- buffer.append("this.").append(col.get(NAME).toString()).append(" = ").append(col.get(NAME).toString()).append(";");
- buffer.append(ENTER);
- buffer.append(TAB);
- buffer.append("}");
- buffer.append(ENTER);
- }
- buffer.append("}");
- buffer.append(ENTER);
- FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\\.", "/") + "/entity/" + className + ".java", buffer.toString());
- }
- /***
- * 生成dao接口interface類的代碼
- * @param table
- * @throws Exception
- */
- public void createDaoClass(String table) throws Exception {
- String className = getClassName(getTableConstantName(table));
- String objectName = StringUtils.uncapitalize(className);
- StringBuilder buffer = new StringBuilder();
- buffer.append("package " + ROOT_PACKAGE + ".dao;").append(ENTER);
- buffer.append("import java.io.Serializable;").append(ENTER);
- buffer.append("import java.util.List;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.dao.EntityDao;").append(ENTER);
- buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("/**\n * @Created:" + NOW_DATE + "\n * @Author " + AUTHOR + "\n");
- buffer.append(" * @Version:").append(Version).append(ENTER);
- buffer.append(" * @Description:").append(className).append(ENTER);
- buffer.append(" * @Email:").append(myEmail).append("\n*/");
- buffer.append(ENTER);
- buffer.append("public interface " + className + "Dao extends EntityDao<" + className + "> {").append(ENTER);
- buffer.append("/**查詢*/").append(ENTER);
- buffer.append(" public List<"+className+"> list(SimplePage simplePage,"+className+" "+objectName+");").append(ENTER);
- buffer.append("/**保存數據*/").append(ENTER);
- buffer.append(" public void saveData("+className+" "+objectName+");").append(ENTER);
- buffer.append("/**更新數據*/").append(ENTER);
- buffer.append(" public void updateData("+className+" "+objectName+");").append(ENTER);
- buffer.append("/**刪除數據*/").append(ENTER);
- buffer.append(" public void deleteData(Long pk);").append(ENTER);
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("}");
- buffer.append(ENTER);
- FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\\.", "/") + "/dao/" + className + "Dao.java", buffer.toString());
- }
- /***
- * 生成dao的實現類的代碼
- * @param table
- * @throws Exception
- */
- public void createDaoImplClass(String table) throws Exception {
- String className = getClassName(getTableConstantName(table));
- String objectName = StringUtils.uncapitalize(className);
- String tableName = StringUtils.lowerCase(getTableConstantName(table));//獲取表名
- StringBuilder buffer = new StringBuilder();
- buffer.append("package " + ROOT_PACKAGE + ".dao.impl;").append(ENTER);
- buffer.append("import java.io.Serializable;").append(ENTER);
- buffer.append("import org.apache.commons.lang3.StringUtils;").append(ENTER);
- buffer.append("import org.springframework.stereotype.Repository;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.dao.impl.EntityDaoSupport;").append(ENTER);
- buffer.append("import com.flong.modules.dao."+className+"Dao;").append(ENTER);
- buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("/**\n * @Created:" + NOW_DATE + "\n * @Author " + AUTHOR + "\n");
- buffer.append(" * @Version:").append(Version).append(ENTER);
- buffer.append(" * @Description:").append(className).append(ENTER);
- buffer.append(" * @Email:").append(myEmail).append("\n*/");
- buffer.append(ENTER);
- buffer.append("@Repository");//這個是spring的註解
- buffer.append(ENTER);
- buffer.append("public class " + className + "DaoImpl extends EntityDaoSupport<" + className + "> implements " + className + "Dao {");
- buffer.append("/**查詢*/").append(ENTER);
- buffer.append(" public List<"+className+"> list(SimplePage simplePage,"+className+" "+objectName+"){").append(ENTER);
- buffer.append(ENTER);
- String mergeField= "";//合併字段.
- //--遍歷獲取列,並拼接字符串,SQL的查詢列,查詢不建議用*去查詢表的全部列.
- for (Map<String, Object> col : getCols(table)){
- //
- if(col.get(NAME).toString()!=null){
- mergeField +=col.get(NAME).toString()+",";//合併字段並用,隔開字段名
- }
- }
- //去掉最後一個,號而後拼接成一個完成的select查詢字段
- if(mergeField!=null){
- mergeField = mergeField.substring(0, mergeField.length()-1);
- }
- buffer.append(" String sql = ").append("\" select "+mergeField+" from ").append(tableName).append(" where 1=1 \" ").append(ENTER);//這個TABLE是實體類的變量
- //daoQuery這個是底層封裝的一個接口,自個能夠更加本身需求封裝.
- buffer.append(" List<"+className+"> list= daoQuery.query(sql,"+className+".class,simplePage);").append(ENTER);
- buffer.append(" return list;").append(ENTER);
- buffer.append("}").append(ENTER);//查詢的結束{
- buffer.append("/**保存數據*/").append(ENTER);
- buffer.append(" public void saveData("+className+" "+objectName+"){").append(ENTER);
- buffer.append(" try {").append(ENTER);
- buffer.append(" saveOrUpdate("+className+");").append(ENTER);
- buffer.append(" } catch (DaoAccessException e) {").append(ENTER);
- buffer.append(" e.printStackTrace();").append(ENTER);
- buffer.append(" }").append(ENTER);
- buffer.append("}");
- buffer.append("/**更新數據*/").append(ENTER);
- buffer.append(" public void updateData("+className+" "+objectName+"){").append(ENTER);
- buffer.append(" try {").append(ENTER);
- buffer.append(" saveOrUpdate("+className+");").append(ENTER);
- buffer.append(" } catch (DaoAccessException e) {").append(ENTER);
- buffer.append(" e.printStackTrace();").append(ENTER);
- buffer.append(" }").append(ENTER);
- buffer.append("}");
- buffer.append("/**刪除數據*/").append(ENTER);
- buffer.append(" public void deleteData(Long pk){").append(ENTER);
- buffer.append(" try {").append(ENTER);
- buffer.append(" delete(pk);").append(ENTER);
- buffer.append(" } catch (DaoAccessException e) {").append(ENTER);
- buffer.append(" e.printStackTrace();").append(ENTER);
- buffer.append(" }").append(ENTER);
- buffer.append("}");
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("}");
- buffer.append(ENTER);
- FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\\.", "/") + "/dao/impl/" + className + "DaoImpl.java", buffer.toString());
- }
- /***
- * 建立Service的接口
- * createServiceClass
- * @param table
- */
- public void createServiceClass(String table) {
- String className = getClassName(getTableConstantName(table));
- String objectName = StringUtils.uncapitalize(className);
- StringBuilder buffer = new StringBuilder();
- buffer.append("package " + ROOT_PACKAGE + ".service;");
- buffer.append("import java.io.Serializable;").append(ENTER);
- buffer.append("import java.util.List;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.dao.EntityDao;").append(ENTER);
- buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("/**\n * @Created:" + NOW_DATE + "\n * @Author " + AUTHOR + "\n");
- buffer.append(" * @Version:").append(Version).append(ENTER);
- buffer.append(" * @Description:").append(className).append(ENTER);
- buffer.append(" * @Email:").append(myEmail).append("\n*/");
- buffer.append(ENTER);
- buffer.append("public interface " + className + "Service {");
- buffer.append("/**查詢*/").append(ENTER);
- buffer.append(" public List<"+className+"> list(SimplePage simplePage,"+className+" "+objectName+");").append(ENTER);
- buffer.append("/**保存數據*/").append(ENTER);
- buffer.append(" public void saveData("+className+" "+objectName+");").append(ENTER);
- buffer.append("/**更新數據*/").append(ENTER);
- buffer.append(" public void updateData("+className+" "+objectName+");").append(ENTER);
- buffer.append("/**刪除數據*/").append(ENTER);
- buffer.append(" public void deleteData(Long pk);").append(ENTER);
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("}");
- buffer.append(ENTER);
- FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\\.", "/") + "/service/" + className + "Service.java", buffer.toString());
- }
- /***
- * 建立Service層的實現類
- * 這裏跟Dao的實現的都繼承了EntityDaoSupport,主要是爲了體現三層service分紅的體驗保留.
- * createServiceImplClass
- * @param table
- */
- public void createServiceImplClass(String table) {
- String className = getClassName(getTableConstantName(table));
- String objectName = StringUtils.uncapitalize(className);
- StringBuilder buffer = new StringBuilder();
- buffer.append("package " + ROOT_PACKAGE + ".service.impl;");
- buffer.append("import java.io.Serializable;").append(ENTER);
- buffer.append("import java.util.List;").append(ENTER);
- buffer.append("import org.springframework.beans.factory.annotation.Autowired;").append(ENTER);
- buffer.append("import org.springframework.stereotype.Service;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.dao.impl.EntityDaoSupport;").append(ENTER);
- buffer.append("import com.flong.modules.dao."+className+"Dao;").append(ENTER);
- buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);
- buffer.append("import com.flong.modules.service."+className+"Service;").append(ENTER);
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("/**\n * @Created:" + NOW_DATE + "\n * @Author " + AUTHOR + "\n");
- buffer.append(" * @Version:").append(Version).append(ENTER);
- buffer.append(" * @Description:").append(className).append(ENTER);
- buffer.append(" * @Email:").append(myEmail).append("\n*/");
- buffer.append(ENTER);
- buffer.append("@Service");
- buffer.append(ENTER);
- buffer.append("public class " + className + "ServiceImpl extends EntityDaoSupport implements " + className + "Service {").append(ENTER);
- buffer.append("@Autowired "+className+"Dao "+objectName+"Dao;");
- buffer.append("/**查詢*/").append(ENTER);
- buffer.append(" public List<"+className+"> list(SimplePage simplePage,"+className+" "+objectName+"){").append(ENTER);
- buffer.append(" return "+objectName+"Dao.list(simplePage,"+objectName+");").append(ENTER);
- buffer.append("}").append(ENTER);//查詢的結束{
- buffer.append("/**保存數據*/").append(ENTER);
- buffer.append(" public void saveData("+className+" "+objectName+"){").append(ENTER);
- buffer.append( objectName+"Dao.saveData("+objectName+");").append(ENTER);
- buffer.append("}");
- buffer.append("/**更新數據*/").append(ENTER);
- buffer.append(" public void updateData("+className+" "+objectName+"){").append(ENTER);
- buffer.append( objectName+"Dao.updateData("+objectName+");").append(ENTER);
- buffer.append("}");
- buffer.append("/**刪除數據*/").append(ENTER);
- buffer.append(" public void deleteData(Long pk){").append(ENTER);
- buffer.append( objectName+"Dao.deleteData(pk);").append(ENTER);
- buffer.append("}");
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("}");
- buffer.append(ENTER);
- FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\\.", "/") + "/service/impl/" + className + "ServiceImpl.java", buffer.toString());
- }
- /***
- * 建立控制層類Controller
- * @param table
- */
- public void createControllerClass(String table){
- //類名
- String className = getClassName(getTableConstantName(table));
- //經過 org.apache.commons.lang3.StringUtils的uncapitalize方法把類名第一個字母轉換成小寫
- String objectName = StringUtils.uncapitalize(className);
- //經過 org.apache.commons.lang3.StringUtils的lowerCase方法把類名整個單詞轉化成小寫而後爲springmvc的路徑返回jsp請求.
- String BASE_PATH="modules/"+StringUtils.lowerCase(className)+"/";//modules+模塊名
- StringBuilder buffer = new StringBuilder();
- /*******處理這個導入須要的類*********/
- buffer.append("import java.util.List;").append(ENTER);
- buffer.append("import javax.servlet.http.HttpServletRequest;").append(ENTER);
- buffer.append("import javax.servlet.http.HttpServletResponse;").append(ENTER);
- buffer.append("import org.springframework.beans.factory.annotation.Autowired;").append(ENTER);
- buffer.append("import org.springframework.stereotype.Controller;").append(ENTER);
- buffer.append("import org.springframework.web.bind.annotation.RequestMapping;").append(ENTER);
- buffer.append("import com.flong.commons.persistence.bean.SimplePage;").append(ENTER);
- buffer.append("import com.flong.commons.web.BaseController;").append(ENTER);
- buffer.append("import com.flong.modules.pojo."+className+";").append(ENTER);
- buffer.append("import com.flong.modules.service."+className+"Service;").append(ENTER);
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("/**\n * @Created:" + NOW_DATE + "\n * @Author " + AUTHOR + "\n");
- buffer.append(" * @Version:").append(Version).append(ENTER);
- buffer.append(" * @Description:").append(className).append(ENTER);
- buffer.append(" * @Email:").append(myEmail).append("\n*/");
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("@Controller").append(ENTER);
- buffer.append("@RequestMapping(\""+StringUtils.lowerCase(className)+"\")");
- buffer.append(ENTER);
- buffer.append("public class " + className + "Controller extends BaseController {");
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append(" @Autowired "+className+"Service " +className+"Service");//注入Service層的接口Name
- buffer.append(ENTER);
- //建立一個默認的查詢..
- buffer.append(ENTER);
- buffer.append(" @RequestMapping(value=\"list\")").append(ENTER);
- buffer.append(" public String list("+className+" "+objectName+",SimplePage simplePage ,HttpServletRequest request ,HttpServletResponse response){");
- buffer.append(ENTER);
- buffer.append(" List<"+className+"> list = "+className+"Service.list(simplePage, "+objectName+");");
- buffer.append(ENTER);
- buffer.append(" request.setAttribute(\""+objectName+"\", object);");
- buffer.append(ENTER);
- buffer.append(" request.setAttribute(\"page\", simplePage);");
- buffer.append(ENTER);
- buffer.append(" request.setAttribute(\"list\", list);");
- buffer.append(ENTER);
- buffer.append(" return \""+BASE_PATH+"list\";");
- buffer.append(ENTER);
- buffer.append(" }");
- buffer.append(ENTER);
- buffer.append("}");
- buffer.append(ENTER);
- FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\\.", "/") + "/controller/" + className + "Controller.java", buffer.toString());
- }
- /***
- * 建立JSP頁面.
- * 以bootstrap3.x爲主.
- * @param table
- */
- public void createJspView(String table)throws Exception{
- String tableConstantName = getTableConstantName(table);
- String className = getClassName(tableConstantName);//獲取類名
- //經過 org.apache.commons.lang3.StringUtils的uncapitalize方法把類名第一個字母轉換成小寫
- String objectName = StringUtils.uncapitalize(className);
- StringBuilder buffer = new StringBuilder();
- buffer.append(" <%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>").append(ENTER);
- //這個就標註一下,這個taglib.jsp文件是JSTL的EL表達式,Spring 標籤,自定義標籤,等的文件。
- buffer.append(" <%@ include file=\"/WEB-INF/views/include/taglib.jsp\"%>").append(ENTER);
- buffer.append(" <!DOCTYPE htm>").append(ENTER);
- buffer.append(" <html>").append(ENTER);
- buffer.append(" <head>").append(ENTER);
- //添加一個插件公共的文件,這個我就不一一備註
- buffer.append(" <%@ include file=\"/WEB-INF/views/include/meta.jsp\"%>").append(ENTER);
- buffer.append(" <%@ include file=\"/WEB-INF/views/include/include.jsp\"%>").append(ENTER);
- buffer.append(" <title></title>").append(ENTER);
- /**=======================添加style===Begin====================**/
- buffer.append(" <style>").append(ENTER);
- buffer.append(" .breadcrumb{").append(ENTER);
- buffer.append(" background-color: #fff;").append(ENTER);
- buffer.append(" }").append(ENTER);
- buffer.append(" .form-search{").append(ENTER);
- buffer.append(" background-color: #fff;").append(ENTER);
- buffer.append(" }").append(ENTER);
- buffer.append(" .form-search1{").append(ENTER);
- buffer.append(" padding: 8px 15px;").append(ENTER);
- buffer.append(" background-color: #f5f5f5;").append(ENTER);
- buffer.append(" }").append(ENTER);
- buffer.append(" </style>").append(ENTER);
- buffer.append(" </head>").append(ENTER);
- /**=======================添加style===End====================**/
- buffer.append("<body>").append(ENTER);
- buffer.append("<ul class=\"nav nav-tabs\">").append(ENTER);
- buffer.append( "<li class=\"active\"><a href=\"${basePath}"+StringUtils.lowerCase(className)+"/list\">"+className+"列表</a></li>").append(ENTER);
- buffer.append("</ul>").append(ENTER);
- buffer.append( " <form:form id=\"searchForm\" modelAttribute=\""+className+"\" action=\"${basePath}"+StringUtils.lowerCase(className)+"/list\" method=\"post\" class=\"breadcrumb form-search form-inline\">").append(ENTER);
- buffer.append(" <div style=\"margin-bottom: 20px;\" class=\"form-search1\">").append(ENTER);
- //這裏能夠判斷數據庫的字段的類型作變量弄處理條件查詢.
- for (Map<String, Object> col : getCols(table)) {
- //判斷若是是數據庫表的字段是DateTime類型的就設值My97DatePicker插件上,方便你們使用.
- if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {
- buffer.append("<input id=\""+col.get(NAME).toString()+"\" name=\""+col.get(NAME).toString()+"\" type=\"text\" readonly=\"readonly\" maxlength=\"20\" class=\"Wdate\"").append(ENTER);
- //在這裏用了$是爲了查詢的時候保留值.
- buffer.append(" value=\"<fmt:formatDate value=\"${"+className+"."+col.get(NAME).toString()+"}\" pattern=\"yyyy-MM-dd HH:mm:ss\"/>\"").append(ENTER);
- buffer.append(" onclick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});\"/>").append(ENTER);
- } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {
- //form:input是spring架構的input標籤path必需要等於實體類要有的屬性.不然會報錯.placeholder是html5有的佔位符的屬性,
- //htmlEscape也是spring的有屬性.在這個jar下面,由於我這個工程是用maven搭建的,全部拷貝的時候,拷貝的時候它帶上路徑.方便你們夥找jar,並且我在這的spring是用3.x
- //C:\Users\liangjilong\.m2\repository\org\springframework\org.springframework.web.servlet\3.1.1.RELEASE\org.springframework.web.servlet-3.1.1.RELEASE.jar
- //org.springframework.web.servlet-3.1.1.RELEASE.jar這個文件下面有一個spring-from.tld文件,能夠找到path,htmlEscape等屬性.
- 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);
- }else{
- 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);
- }
- buffer.append(ENTER);
- }
- //btn btn-info這個樣式用過bootstrap的人都知道這個是.
- buffer.append(" <input id=\"btnSubmit\" class=\"btn btn-info\" type=\"submit\" value=\"查詢\"/>").append(ENTER);
- buffer.append(" </div>").append(ENTER);
- buffer.append("<table id=\"contentTable\" class=\"table table-striped table-bordered table-hover\">").append(ENTER);
- buffer.append("<thead>").append(ENTER);//thead標籤End
- buffer.append("<tr>").append(ENTER);//tr標籤End
- /*******遍歷列表的th的列*****/
- for (Map<String, Object> col : getTableRemarks(table)) {
- for (String k : col.keySet()){
- String colName = col.get(k).toString();
- buffer.append("<th>").append(colName).append("</th>");
- buffer.append(ENTER);
- }
- }
- buffer.append("<th>操做</th> ");
- buffer.append(ENTER);
- buffer.append("</tr>").append(ENTER);
- buffer.append("</thead>").append(ENTER);
- buffer.append("<tbody>").append(ENTER);
- /*******遍歷列表的td的列*****/
- buffer.append(" <c:forEach items=\"${list}\" var=\""+objectName+"\" varStatus=\"row\">").append(ENTER);
- buffer.append(" <tr>").append(ENTER);
- buffer.append(" <td>${row.index+1 }</td>").append(ENTER);
- for (Map<String, Object> col : getCols(table)) {
- buffer.append(" <td>");
- if(Class.forName(col.get(CLASS).toString()).isAssignableFrom(Date.class) || Class.forName(col.get(CLASS).toString()) == Timestamp.class) {
- //若是是Date類型就轉換用EL表達式格式化fmt:formatDate
- buffer.append("<fmt:formatDate value=\"${"+objectName+"."+col.get(NAME).toString()+"}\" type=\"date\" dateStyle=\"long\"/>");
- } else if(getClassName(col.get(NAME).toString()).equals(Class.forName(col.get(CLASS).toString()).getSimpleName())) {
- buffer.append(" ${"+objectName+"."+col.get(NAME).toString()+"}" );
- }else{
- buffer.append(" ${"+objectName+"."+col.get(NAME).toString()+"}" );
- }
- buffer.append("</td>");
- buffer.append(ENTER);
- }
- buffer.append(" </tr>").append(ENTER);
- buffer.append(" </c:forEach>").append(ENTER);
- buffer.append("</tbody>").append(ENTER);//tbody標籤結束.
- buffer.append("</table>").append(ENTER);
- //這個是pagination.jsp是分頁文件.
- buffer.append("<%@ include file=\"/WEB-INF/views/include/pagination.jsp\"%>").append(ENTER);
- buffer.append("</form:form>").append(ENTER);//form:form標籤結束.
- buffer.append("</body>").append(ENTER);//body標籤結束.
- buffer.append("</html>").append(ENTER);//html標籤結束.
- buffer.append(ENTER);
- buffer.append(ENTER);
- FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\\.", "/") + "/jsp/" + className + ".jsp", buffer.toString());
- }
- /***
- * 建立表的類定義常量
- * @param tables
- */
- public void createTableClass(List<String> tables) {
- StringBuilder buffer = new StringBuilder();
- buffer.append("package " + ROOT_PACKAGE + ".domain;");
- buffer.append(ENTER);
- buffer.append(ENTER);
- buffer.append("/**\n * @Created:" + NOW_DATE + "\n * @Author " + AUTHOR + "\n");
- buffer.append(" * @Version:").append(Version).append(ENTER);
- buffer.append(" * @Email:").append(myEmail).append("\n*/");
- buffer.append(ENTER);
- buffer.append("public interface Table {");
- buffer.append(ENTER);
- for (String table : tables) {
- buffer.append(TAB);
- buffer.append("String " + getTableConstantName(table) + " = \"" + table.toUpperCase() + "\";");
- buffer.append(ENTER);
- }
- buffer.append(ENTER);
- buffer.append("}");
- buffer.append(ENTER);
- FileUtils.save("output-code/" + ROOT_PACKAGE.replaceAll("\\.", "/") + "/domain/Table.java", buffer.toString());
- }
- /***
- * 獲取數據庫表名
- * @return
- * @throws Exception
- */
- public List<String> getTables() throws Exception {
- List<Object> params = new ArrayList<Object>();
- //System.out.println("==========="+DB_NAME);
- //params.add(DB_NAME);
- String dbname=DB_NAME;
- params.add(dbname);
- ResultSet rs = DBHelperUtils.query("select table_name from information_schema.tables where table_schema = ? order by table_name", params);
- List<String> tables = new ArrayList<String>();
- while (rs.next()) {
- tables.add(rs.getString(1));
- }
- return tables;
- }
- /***
- * 列名 類型 => 說明
- * TABLE_CAT String => 表 catalog
- * TABLE_SCHEM String => 表 schema
- * TABLE_NAME String => 表名
- * TABLE_TYPE String => 表類型
- * REMARKS String => 表註釋
- * 獲取表的列
- * @param table
- * @return
- * @throws Exception
- */
- private List<Map<String, Object>> getCols(String table) throws Exception {
- List<Map<String, Object>> cols = new ArrayList<Map<String,Object>>();
- ResultSetMetaData md = DBHelperUtils.query("select * from " + table + " where 1 = 2", null).getMetaData();
- for (int i = 1; i <= md.getColumnCount(); i++) {
- Map<String, Object> col = new HashMap<String, Object>();
- cols.add(col);
- col.put(NAME, md.getColumnName(i));
- col.put(CLASS, md.getColumnClassName(i));
- col.put(SIZE, md.getColumnDisplaySize(i));
- col.put(REMARKS, md.getColumnName(i));
- /* System.out.println("1"+ md.getCatalogName(i));
- System.out.println("2"+ md.getColumnClassName(i));
- System.out.println("3"+ md.getColumnDisplaySize(i));
- System.out.println("4"+ md.getColumnType(i));
- System.out.println("5"+ md.getSchemaName(i));
- System.out.println("6"+ md.getPrecision(i));
- System.out.println("7"+ md.getScale(i));*/
- String _type = null;
- String type = md.getColumnTypeName(i);
- if(type.equals("INT")) {
- _type = "INTEGER";
- } else if(type.equals("DATETIME")) {
- _type = "TIMESTAMP";
- } else {
- _type = type;
- }
- col.put(TYPE, _type);
- }
- return cols;
- }
- /**
- * 獲取全部表
- * @param conn
- * @throws SQLException
- */
- public static List<Map<String, Object>> getAllTable() throws SQLException {
- /**
- * 定義一個Lis
- */
- List<Map<String, Object>> cols = new ArrayList<Map<String,Object>>();
- DatabaseMetaData metaData = DBHelperUtils.getInstance().getDatabaseMetaData();
- //這個是獲取全部表.
- ResultSet rs = metaData.getTables(null, "%", "%", new String[] {"TABLE"});
- while (rs.next()) {
- String tableName = rs.getString("TABLE_NAME");////這個是獲取表名
- if(tableName!=null){
- Map<String, Object> col = new HashMap<String, Object>();
- // rs =getConnection.getMetaData().getColumns(null, getXMLConfig.getSchema(),tableName.toUpperCase(), "%");
- //其餘數據庫不須要這個方法的,直接傳null,這個是oracle和db2這麼用
- ResultSet rs1 = metaData.getColumns(null, "%", tableName, "%");
- while(rs1.next()){
- String COLUMN_NAME = rs1.getString("COLUMN_NAME");
- String REMARKS = rs1.getString("REMARKS");
- //先判斷備註是否爲空,不爲空就取表的字段的註釋說明,不然的話就去字段列名
- if(REMARKS==null||REMARKS==""){
- col.put(COLUMN_NAME, COLUMN_NAME);
- }else{
- col.put(REMARKS, REMARKS);
- }
- cols.add(col);
- }
- }
- }
- return cols;
- }
- /***
- * 獲取列的備註
- * @param table
- * @return
- * @throws SQLException
- */
- public static List<Map<String, Object>> getTableRemarks(String table) throws SQLException {
- List<Map<String, Object>> cols = new ArrayList<Map<String,Object>>();
- Connection conn=DBHelperUtils.getInstance().getConnection();
- DatabaseMetaData metaData = conn.getMetaData();
- ResultSet rs = metaData.getTables(null, "%", "%", new String[] {"TABLE"});
- while (rs.next()) {
- String tableName = rs.getString("TABLE_NAME");
- //傳進來的表名和查詢出來的表名做對比,而且是忽略大小寫
- if(tableName!=null){
- if(table.equalsIgnoreCase(tableName)){
- Map<String, Object> col = new HashMap<String, Object>();
- //Map<String, Object> col = new HashTable<String, Object>();
- ResultSet rs1 = metaData.getColumns(null, "%", tableName, "%");
- while(rs1.next()){
- String COLUMN_NAME = rs1.getString("COLUMN_NAME");
- String REMARKS = rs1.getString("REMARKS");
- //先判斷備註是否爲空,不爲空就取表的字段的註釋說明,不然的話就去字段列名
- if(REMARKS==null||REMARKS==""){
- col.put(COLUMN_NAME, COLUMN_NAME);
- }else{
- col.put(REMARKS, REMARKS);
- }
- //去掉重複的數據
- col = removeRepeatData();
- cols.add(col);
- }
- break;
- }
- }
- }
- return cols;
- }
- /**
- * 獲取表的主鍵.
- * @param tableName
- */
- public static String getTablePrimaryKeys(String tableName)throws Exception{
- DatabaseMetaData metaData = DBHelperUtils.getInstance().getDatabaseMetaData();
- ResultSet pkRSet = metaData.getPrimaryKeys(null, null, tableName);
- String primaryKey = "";
- if(pkRSet.next() ) {
- //把這個列的名稱獲取出來
- primaryKey = pkRSet.getString("PK_NAME");//PK_NAME/COLUMN_NAME
- primaryKey=(primaryKey==null?"":primaryKey);
- System.out.println(primaryKey);
- }
- return primaryKey;
- }
- /**
- * 獲取表的主鍵和外鍵包括外鍵表的名
- * @param tableName
- */
- public static String[] getTablePrimaryKeyForeignKey(String tableName)throws Exception{
- DatabaseMetaData metaData = DBHelperUtils.getInstance().getDatabaseMetaData();
- ResultSet fkSet = metaData.getPrimaryKeys(null, null, tableName);
- String pkColumnName="",fkColumnName="",pkTablenName="";
- String [] paramsKey= new String[3];
- while(fkSet.next()){
- pkColumnName = fkSet.getString("PK_NAME");//主鍵在網查到的有多是PKCOLUMN_NAME
- fkColumnName = fkSet.getString("FK_NAME");//外鍵網查到的有多是PKCOLUMN_NAME
- pkTablenName = fkSet.getString("PKTABLE_NAME");//主鍵表名
- //System.out.println(pkColumnName+fkColumnName+pkTablenName);
- pkColumnName=(pkColumnName==null?"":pkColumnName);
- fkColumnName=(fkColumnName==null?"":fkColumnName);
- pkTablenName=(pkTablenName==null?"":pkTablenName);
- paramsKey[0]=fkColumnName;
- paramsKey[1]=fkColumnName;
- paramsKey[2]=pkTablenName;
- }
- return paramsKey;
- }
- /***
- * 去掉重複的數據
- * @return
- */
- private static Map<String, Object> removeRepeatData() {
- Map<String, Object> col = new HashMap<String, Object>();
- Set<String> keySet = col.keySet();
- for (String str : keySet) {
- col.put(str, str);
- }
- return col;
- }
- /***
- * 獲取表的常量名,通常是在數據庫建表的時候,寫的註釋..
- * @param table
- * @return
- */
- private String getTableConstantName(String table) {
- String tableConstantName = table.toUpperCase();
- for (String item : IGNORE_TABLE_PREFIX) {
- tableConstantName = tableConstantName.replaceAll("^" + item.toUpperCase(), "");
- }
- return tableConstantName;
- }
- /***
- * 獲取類的名
- * @param name
- * @return
- */
- private String getClassName(String name) {
- String[] names = name.split("_");
- StringBuilder sb = new StringBuilder();
- for (String n : names) {
- if(n.length() == 0) {
- sb.append("_");
- } else {
- sb.append(n.substring(0, 1).toUpperCase());
- if(n.length() > 1) {
- sb.append(n.substring(1).toLowerCase());
- }
- }
- }
- return sb.toString();
- }
- /**
- * 獲取字段名
- * @param name
- * @return
- */
- private String getFieldName(String name) {
- String _name = getClassName(name);
- return _name.substring(0, 1).toLowerCase() + _name.substring(1);
- }
- /**
- * 轉換成泛型Map
- * @param limit
- * @param rs
- * @return
- * @throws SQLException
- */
- public static List<Map> toListMap(int limit, ResultSet rs)throws SQLException {
- ResultSetMetaData rsmd = rs.getMetaData();
- int count = 0;
- List list = new ArrayList();
- while (rs.next()) {
- Map row = new HashMap();
- for (int i = 1; i <= rsmd.getColumnCount(); i++) {
- row.put(rsmd.getColumnName(i), rs.getObject(i));
- }
- list.add(row);
- count++;
- if (count >= limit) {
- break;
- }
- }
- return list;
- }
- /***
- * 獲取查詢list
- * @param conn
- * @param sql
- * @param limit
- * @return
- * @throws SQLException
- */
- public static List<Map> queryForList(Connection conn, String sql, int limit)throws SQLException {
- PreparedStatement ps = conn.prepareStatement(sql.trim());
- ps.setMaxRows(limit);
- ps.setFetchDirection(1000);
- ResultSet rs = ps.executeQuery();
- return toListMap(limit, rs);
- }
- /***
- * 獲取查詢list
- * @param conn
- * @param sql
- * @param limit
- * @return
- * @throws SQLException
- */
- public static List<Map> queryForList(String sql, int limit) throws SQLException {
- Connection conn = DBHelperUtils.getConnection();
- return queryForList(conn, sql, limit);
- }
- /***
- * 生成全部Entity,Dao,Service,Controller,JSP 代碼
- * @throws Exception
- */
- public void createAllCodeGenerator()throws Exception{
- List<String> tables = getTables();
- for (String table : tables) {
- createEntityClass(table);//this is method create Entity
- createDaoClass(table);//this is method create Dao Interface
- createDaoImplClass(table);//this is method create Dao implement
- createServiceClass(table);//this is method create Service Interface
- createServiceImplClass(table);//this is method create Service implement
- createControllerClass(table);//this is method create Controller
- createJspView(table);//this is method JspView
- }
- createTableClass(tables);
- }
- public static void main(String[] args)throws Exception {
- String sql="select * from SYS_MENU ";
- //List<Map> queryForList = queryForList(sql, 1000);
- /*for(Map m:queryForList){
- System.out.println("======"+m);
- }*/
- String tableName = "SYS_MENU";//表名
- /* List<Map<String, Object>> tableRemarks = getTableRemarks(tableName);
- int i=0;
- for (Map<String, Object> col : getTableRemarks(tableName)) {
- Set<String> keySet = col.keySet();
- for (Object str : keySet) {
- //System.out.println(str);
- }
- }
- */
- //getTablePrimaryKeys("test");
- //new CodeGenerator().createJspView("sup_email");
- new CodeGenerator().createEntityClass("test");
- //new CodeGenerator().getTablePrimaryKeyForeignKey("test");
- //String myId="My_id";
- //boolean endsWith = myId.toString().toUpperCase().endsWith("_ID");
- //if(col.get(NAME).toString().equalsIgnoreCase("ID") || col.get(NAME).toString().toUpperCase().endsWith("_ID"))
- //if(endsWith){
- //System.out.println(11111);
- //}
- //createAllCodeGenerator();
- }
- }
- package com.flong.codegenerator;
- import java.sql.Connection;
- import java.sql.DatabaseMetaData;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.List;
- /***
- *@Author:liangjilong
- *@Date:2015年12月5日下午12:25:12
- *@Email:jilongliang@sina.com
- *@Version:1.0
- *@CopyRight(c)Flong Intergrity Ltd.
- */
- @SuppressWarnings("all")
- public class DBHelperUtils {
- private static final Connection conn;
- private static final String driverClass = PropertiesHelper.getValueByKey("jdbc.driver");
- private static final String connectionUrl = PropertiesHelper.getValueByKey("jdbc.url");
- private static final String username = PropertiesHelper.getValueByKey("jdbc.username");
- private static final String password = PropertiesHelper.getValueByKey("jdbc.password");
- private static DBHelperUtils instance = null;
- /**
- * 定義代碼塊.
- */
- static {
- try {
- Class.forName(driverClass);
- conn = DriverManager.getConnection(connectionUrl, username, password);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**創建單例模式
- * Single
- * @return
- */
- public static DBHelperUtils getInstance() {
- if (instance == null) {
- synchronized (DBHelperUtils.class) {
- instance = new DBHelperUtils();
- }
- }
- return instance;
- }
- /**
- * 查詢數據
- * @param sql
- * @param params
- * @return
- */
- public static ResultSet query(String sql, List<Object> params) {
- System.out.println("sql: " + sql);
- //System.out.println("params: " + params);
- try {
- PreparedStatement psmt = conn.prepareStatement(sql);
- if(params != null) {
- for (int i = 0; i < params.size(); i++) {
- psmt.setObject(i+1, params.get(i));
- }
- }
- return psmt.executeQuery();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
- /***
- * 更新
- * @param sql
- * @param params
- */
- public static void update(String sql, List<Object> params) {
- System.out.println("sql: " + sql);
- //System.out.println("params: " + params);
- try {
- PreparedStatement psmt = conn.prepareStatement(sql);
- if(params != null) {
- for (int i = 0; i < params.size(); i++) {
- psmt.setObject(i+1, params.get(i));
- }
- }
- psmt.executeUpdate();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * 獲取連接
- * @return
- */
- public static Connection getConnection(){
- try {
- Class.forName(driverClass);
- return DriverManager.getConnection(connectionUrl, username, password);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 獲取數據DatabaseMetaData對象
- * @return
- */
- public DatabaseMetaData getDatabaseMetaData(){
- try {
- return getInstance().getConnection().getMetaData();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 得到數據庫的一些相關信息
- */
- public void getDataBaseInformations() {
- try {
- System.out.println("數據庫已知的用戶: "+ getDatabaseMetaData().getUserName());
- System.out.println("數據庫的系統函數的逗號分隔列表: "+ getDatabaseMetaData().getSystemFunctions());
- System.out.println("數據庫的時間和日期函數的逗號分隔列表: "+ getDatabaseMetaData().getTimeDateFunctions());
- System.out.println("數據庫的字符串函數的逗號分隔列表: "+ getDatabaseMetaData().getStringFunctions());
- System.out.println("數據庫供應商用於 'schema' 的首選術語: "+ getDatabaseMetaData().getSchemaTerm());
- System.out.println("數據庫URL: " + getDatabaseMetaData().getURL());
- System.out.println("是否容許只讀:" + getDatabaseMetaData().isReadOnly());
- System.out.println("數據庫的產品名稱:" + getDatabaseMetaData().getDatabaseProductName());
- System.out.println("數據庫的版本:" + getDatabaseMetaData().getDatabaseProductVersion());
- System.out.println("驅動程序的名稱:" + getDatabaseMetaData().getDriverName());
- System.out.println("驅動程序的版本:" + getDatabaseMetaData().getDriverVersion());
- System.out.println();
- System.out.println("數據庫中使用的表類型");
- ResultSet rs = getDatabaseMetaData().getTableTypes();
- while (rs.next()) {
- System.out.println(rs.getString(1));
- }
- rs.close();
- System.out.println();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- /**
- * 得到該用戶下面的全部表
- */
- public void getAllTableList(String schemaName) {
- try {
- // table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
- String[] types = { "TABLE" };
- ResultSet rs = getDatabaseMetaData().getTables(null, schemaName, "%", types);
- while (rs.next()) {
- String tableName = rs.getString("TABLE_NAME"); //表名
- String tableType = rs.getString("TABLE_TYPE"); //表類型
- String remarks = rs.getString("REMARKS"); //表備註
- System.out.println(tableName + "-" + tableType + "-" + remarks);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- /**
- * 得到該用戶下面的全部視圖
- */
- public void getAllViewList(String schemaName) {
- try{
- String[] types = { "VIEW" };
- ResultSet rs = getDatabaseMetaData().getTables(null, schemaName, "%", types);
- while (rs.next()){
- String viewName = rs.getString("TABLE_NAME"); //視圖名
- String viewType = rs.getString("TABLE_TYPE"); //視圖類型
- String remarks = rs.getString("REMARKS"); //視圖備註
- System.out.println(viewName + "-" + viewType + "-" + remarks);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- /**
- * 得到數據庫中全部方案名稱
- */
- public void getAllSchemas(){
- try{
- ResultSet rs = getDatabaseMetaData().getSchemas();
- while (rs.next()){
- String tableSchem = rs.getString("TABLE_SCHEM");
- System.out.println(tableSchem);
- }
- } catch (SQLException e){
- e.printStackTrace();
- }
- }
- /**
- * 得到表或視圖中的全部列信息
- */
- public void getTableColumns(String schemaName, String tableName) {
- try{
- ResultSet rs = getDatabaseMetaData().getColumns(null, schemaName, tableName, "%");
- while (rs.next()){
- String tableCat = rs.getString("TABLE_CAT");//表目錄(可能爲空)
- String tableSchemaName = rs.getString("TABLE_SCHEM");//表的架構(可能爲空)
- String tableName_ = rs.getString("TABLE_NAME");//表名
- String columnName = rs.getString("COLUMN_NAME");//列名
- int dataType = rs.getInt("DATA_TYPE"); //對應的java.sql.Types類型
- String dataTypeName = rs.getString("TYPE_NAME");//java.sql.Types類型 名稱
- int columnSize = rs.getInt("COLUMN_SIZE");//列大小
- int decimalDigits = rs.getInt("DECIMAL_DIGITS");//小數位數
- int numPrecRadix = rs.getInt("NUM_PREC_RADIX");//基數(一般是10或2)
- int nullAble = rs.getInt("NULLABLE");//是否容許爲null
- String remarks = rs.getString("REMARKS");//列描述
- String columnDef = rs.getString("COLUMN_DEF");//默認值
- int sqlDataType = rs.getInt("SQL_DATA_TYPE");//sql數據類型
- int sqlDatetimeSub = rs.getInt("SQL_DATETIME_SUB"); //SQL日期時間分?
- int charOctetLength = rs.getInt("CHAR_OCTET_LENGTH"); //char類型的列中的最大字節數
- int ordinalPosition = rs.getInt("ORDINAL_POSITION"); //表中列的索引(從1開始)
- /**
- * ISO規則用來肯定某一列的爲空性。
- * 是---若是該參數能夠包括空值;
- * 無---若是參數不能包含空值
- * 空字符串---若是參數爲空性是未知的
- */
- String isNullAble = rs.getString("IS_NULLABLE");
- /**
- * 指示此列是不是自動遞增
- * 是---若是該列是自動遞增
- * 無---若是不是自動遞增列
- * 空字串---若是不能肯定它是否
- * 列是自動遞增的參數是未知
- */
- String isAutoincrement = rs.getString("IS_AUTOINCREMENT");
- System.out.println(tableCat + "-" + tableSchemaName + "-" + tableName_ + "-" + columnName + "-"
- + dataType + "-" + dataTypeName + "-" + columnSize + "-" + decimalDigits + "-" + numPrecRadix
- + "-" + nullAble + "-" + remarks + "-" + columnDef + "-" + sqlDataType + "-" + sqlDatetimeSub
- + charOctetLength + "-" + ordinalPosition + "-" + isNullAble + "-" + isAutoincrement + "-");
- }
- } catch (SQLException e){
- e.printStackTrace();
- }
- }
- /**
- * 得到一個表的索引信息
- */
- public void getIndexInfo(String schemaName, String tableName) {
- try{
- ResultSet rs = getDatabaseMetaData().getIndexInfo(null, schemaName, tableName, true, true);
- while (rs.next()){
- boolean nonUnique = rs.getBoolean("NON_UNIQUE");//非惟一索引(Can index values be non-unique. false when TYPE is tableIndexStatistic )
- String indexQualifier = rs.getString("INDEX_QUALIFIER");//索引目錄(可能爲空)
- String indexName = rs.getString("INDEX_NAME");//索引的名稱
- short type = rs.getShort("TYPE");//索引類型
- short ordinalPosition = rs.getShort("ORDINAL_POSITION");//在索引列順序號
- String columnName = rs.getString("COLUMN_NAME");//列名
- String ascOrDesc = rs.getString("ASC_OR_DESC");//列排序順序:升序仍是降序
- int cardinality = rs.getInt("CARDINALITY"); //基數
- System.out.println(nonUnique + "-" + indexQualifier + "-" + indexName + "-" + type + "-" + ordinalPosition + "-" + columnName + "-" + ascOrDesc + "-" + cardinality);
- }
- } catch (SQLException e){
- e.printStackTrace();
- }
- }
- /**
- * 得到一個表的主鍵信息
- */
- public void getAllPrimaryKeys(String schemaName, String tableName) {
- try{
- ResultSet rs = getDatabaseMetaData().getPrimaryKeys(null, schemaName, tableName);
- while (rs.next()){
- String columnName = rs.getString("COLUMN_NAME");//列名
- short keySeq = rs.getShort("KEY_SEQ");//序列號(主鍵內值1表示第一列的主鍵,值2表明主鍵內的第二列)
- String pkName = rs.getString("PK_NAME"); //主鍵名稱
- System.out.println(columnName + "-" + keySeq + "-" + pkName);
- }
- }catch (SQLException e){
- e.printStackTrace();
- }
- }
- /**
- * 得到一個表的外鍵信息
- */
- public void getAllExportedKeys(String schemaName, String tableName) {
- try{
- ResultSet rs = getDatabaseMetaData().getExportedKeys(null, schemaName, tableName);
- while (rs.next()){
- String pkTableCat = rs.getString("PKTABLE_CAT");//主鍵表的目錄(可能爲空)
- String pkTableSchem = rs.getString("PKTABLE_SCHEM");//主鍵表的架構(可能爲空)
- String pkTableName = rs.getString("PKTABLE_NAME");//主鍵表名
- String pkColumnName = rs.getString("PKCOLUMN_NAME");//主鍵列名
- String fkTableCat = rs.getString("FKTABLE_CAT");//外鍵的表的目錄(可能爲空)出口(可能爲null)
- String fkTableSchem = rs.getString("FKTABLE_SCHEM");//外鍵表的架構(可能爲空)出口(可能爲空)
- String fkTableName = rs.getString("FKTABLE_NAME");//外鍵表名
- String fkColumnName = rs.getString("FKCOLUMN_NAME"); //外鍵列名
- short keySeq = rs.getShort("KEY_SEQ");//序列號(外鍵內值1表示第一列的外鍵,值2表明在第二列的外鍵)。
- /**
- * hat happens to foreign key when primary is updated:
- * importedNoAction - do not allow update of primary key if it has been imported
- * importedKeyCascade - change imported key to agree with primary key update
- * importedKeySetNull - change imported key to NULL if its primary key has been updated
- * importedKeySetDefault - change imported key to default values if its primary key has been updated
- * importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
- */
- short updateRule = rs.getShort("UPDATE_RULE");
- /**
- * What happens to the foreign key when primary is deleted.
- * importedKeyNoAction - do not allow delete of primary key if it has been imported
- * importedKeyCascade - delete rows that import a deleted key
- * importedKeySetNull - change imported key to NULL if its primary key has been deleted
- * importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
- * importedKeySetDefault - change imported key to default if its primary key has been deleted
- */
- short delRule = rs.getShort("DELETE_RULE");
- String fkName = rs.getString("FK_NAME");//外鍵的名稱(可能爲空)
- String pkName = rs.getString("PK_NAME");//主鍵的名稱(可能爲空)
- /**
- * can the evaluation of foreign key constraints be deferred until commit
- * importedKeyInitiallyDeferred - see SQL92 for definition
- * importedKeyInitiallyImmediate - see SQL92 for definition
- * importedKeyNotDeferrable - see SQL92 for definition
- */
- short deferRability = rs.getShort("DEFERRABILITY");
- System.out.println(pkTableCat + "-" + pkTableSchem + "-" + pkTableName + "-" + pkColumnName + "-"
- + fkTableCat + "-" + fkTableSchem + "-" + fkTableName + "-" + fkColumnName + "-" + keySeq + "-"
- + updateRule + "-" + delRule + "-" + fkName + "-" + pkName + "-" + deferRability);
- }
- } catch (SQLException e){
- e.printStackTrace();
- }
- }
- public void closeResource() {
- try {
- if (conn != null) {
- conn.close();
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws Exception {
- DBHelperUtils metaData = new DBHelperUtils();
- metaData.getDataBaseInformations();
- metaData.getAllTableList(null);
- metaData.getAllViewList(null);
- metaData.getAllSchemas();
- metaData.getTableColumns(null, "test");
- metaData.getIndexInfo(null, "test");
- metaData.getAllPrimaryKeys(null, "test");
- metaData.getAllExportedKeys(null, "test");
- }
- }
- package com.flong.codegenerator;
- import java.io.File;
- import java.io.FileWriter;
- public class FileUtils {
- /**
- * 把生成的文件都保存.
- * @param path
- * @param data
- */
- public static void save(String path, String data) {
- try {
- File file = new File(path);
- File dir = new File(path.substring(0, path.lastIndexOf("/")));
- if(!dir.exists()) {
- dir.mkdirs();
- }
- FileWriter out = new FileWriter(file);
- out.write(data);
- out.flush();
- out.close();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
- package com.flong.codegenerator;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Properties;
- /***
- *@Author:liangjilong
- *@Date:2015年12月5日下午12:25:12
- *@Email:jilongliang@sina.com
- *@Version:1.0
- *@CopyRight(c)Flong Intergrity Ltd.
- *@Description:讀取文properties
- */
- public class PropertiesHelper {
- private static final Map<String, String> properties = new HashMap<String, String>();
- static {
- try {
- Properties pps = new Properties();
- pps.load(PropertiesHelper.class.getClassLoader().getResourceAsStream("prop/DBSource.properties"));
- //處理重複的值.
- for (Entry<Object, Object> entry : pps.entrySet()) {
- properties.put(entry.getKey().toString().trim(), entry.getValue().toString().trim());
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- *經過key值去獲取值.
- */
- public static String getValueByKey(String name) {
- return properties.get(name);
- }
- }
- #mysql database setting
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
- jdbc.username=root
- jdbc.password=root
其中源碼在一個CodeGenerator.Java裏面javascript
SQL生成器和代碼生成器源代碼下載地址 http://download.csdn.NET/detail/l_ji_l/9797834html
http://jilongliang.iteye.com/blog/2366511html5