根據資料庫自動生成java程式碼
阿新 • • 發佈:2018-12-25
package com.power.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import sun.nio.cs.FastCharsetProvider; /** * @author chengwei * @date 2017年3月10日 下午6:11:02 * @version V1.0 * @Description: 根據資料庫生成實體類,Mapper,mapper.xml,Service等檔案 */ public class EntityUtil { // 定義資料庫常用型別 private static final String TYPE_CHAR = "char"; private static final String TYPE_DATE = "date"; private static final String TYPE_TIMESTAMP = "timestamp"; private static final String TYPE_INT = "int"; private static final String TYPE_BIGINT = "bigint"; private static final String TYPE_TEXT = "text"; private static final String TYPE_BIT = "bit"; private static final String TYPE_DECIMAL = "decimal"; private static final String TYPE_BLOB = "blob"; // 配置檔案存放地址 private static final String PACKAGEPATH = "D:\\workspace\\entity\\"; private static final String BEAN_PATH = PACKAGEPATH + "entity_bean"; private static final String DTO_PATH = PACKAGEPATH + "entity_vo"; private static final String SERVICE_PATH = PACKAGEPATH + "entity_service"; private static final String MAPPER_PATH = PACKAGEPATH + "entity_mapper"; private static final String XML_PATH = PACKAGEPATH + "entity_mapper/xml"; // 配置檔案包名稱 , 這些值需要根據各自的專案配置 private static final String MODULENAME = "com.goldmantis.appjia"; private static final String BEAN_PACKAGE = MODULENAME + ".model.wms"; private static final String DTO_PACKAGE = MODULENAME + ".model.vo"; private static final String MAPPER_PACKAGE = MODULENAME + ".dao.wms"; private static final String SERVICE_PACKAGE = MODULENAME + ".service.wms"; private static final String SERVICEIMPL_PACKAGE = MODULENAME + ".service.wms.impl"; private static final String CONTROLLER_PACKAGE = MODULENAME + ".controller"; // 配置資料庫連線資訊 private static final String DRIVERNAME = "com.mysql.jdbc.Driver"; private static final String USER = "root"; private static final String PASSWORD = "123456"; private static final String URL = "jdbc:mysql://localhost:3306/jia_erp?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false"; // 方法統一命名 private static final String save = "insert"; private static final String saveSelective = "insertSelective"; private static final String update = "updateByPrimaryKey"; private static final String updateSelective = "updateByPrimaryKeySelective"; private static final String countTotalNum = "count"; private static final String queryPage = "list"; private static final String queryById = " selectByPrimaryKey"; private static final String delete = "deleteByPrimaryKey"; // sql語句 private static final String showTablesName = "show tables"; // 獲取資料庫的所有表名 private static final String showTablesInfo = "show table status"; // 獲取資料庫的所有表詳情資訊(包括註釋) private static final String showFields = "show full fields from "; // 獲取指定表的所有欄位詳情 // 定義系統中使用到的全域性變數 private String tableName; private String beanName; private String dtoName; private String serviceName; private String serviceImplName; private String controllerName; private String lowerBeanName; private String mapperName; private List columns = new ArrayList<>(); private List types = new ArrayList<>(); private List comments = new ArrayList<>(); private Connection conn; // 常用的配置項 /** 用於指定生成類檔案的表, 當值為空時會將資料庫的所有表都生成類檔案 */ private static final String TABLE_NAME = ""; /** 表名中的這些值將不會轉換為類名的一部分 */ private static final String[] TABLE_PREFIXS = {"app","bi","jia","lms","p","web","wms","zwms", "v2"}; /** 指定是否生成分頁查詢方法, false為不生成, true為生成 */ private Boolean useListMeathod = false; /** * 刪除指定目錄下所有檔案,若目錄不存在則建立該目錄 */ private static void mkdirs(Runtime runtime) throws IOException { File file = new File(PACKAGEPATH); if (file.exists()) { runtime.exec("cmd /c del /q/a/f/s "+ file.getAbsolutePath()); } file.mkdirs(); } /** * 獲取連線 */ private void initConnection() throws ClassNotFoundException, SQLException { Class.forName(DRIVERNAME); conn = DriverManager.getConnection(URL, USER, PASSWORD); } /** * 獲取所有的表名 */ private List getTables() throws SQLException { List tables = new ArrayList<>(); PreparedStatement pstate = conn.prepareStatement(showTablesName); ResultSet results = pstate.executeQuery(); while (results.next()) { String tableName = results.getString(1); // if ( tableName.toLowerCase().startsWith("yy_") ) { tables.add(tableName); // } } return tables; } /** * 根據表名生成實體類名稱及所有相關的檔名 */ private void initNameByTable(String table) { tableName = table; beanName = getBeanName(table); lowerBeanName = lowerCaseFirstLitter(beanName); dtoName = beanName + "Vo"; mapperName = beanName + "Mapper"; serviceName = beanName + "Service"; serviceImplName = serviceName + "Impl"; controllerName = beanName + "Controller"; } /** * 根據表名獲取實體類名 */ private String getBeanName(String table) { StringBuilder entityName = new StringBuilder(table.length()); String tableLower = table.toLowerCase(); String[] tables = tableLower.split("_"); String temp = null; for (int i = 0; i < tables.length; i++) { temp = tables[i].trim(); if(canUseTemp(temp)){ entityName.append(upperCaseFirstLitter(temp)); } } return entityName.toString(); } /** * 判斷表名字首是否要加到實體類名上 */ private Boolean canUseTemp(String temp) { if(isEmpty(temp)){ return false; } for(String tablePrefix: TABLE_PREFIXS){ if (tablePrefix.equalsIgnoreCase(temp)) { return false; } } return true; } /** * 獲取實體類屬性的資料型別 */ private String processType(String type) { if (type.indexOf(TYPE_CHAR) > -1) { return "String"; } else if (type.indexOf(TYPE_BIGINT) > -1) { return "Long"; } else if (type.indexOf(TYPE_INT) > -1) { return "Integer"; } else if (type.indexOf(TYPE_DATE) > -1) { return "Date"; } else if (type.indexOf(TYPE_TEXT) > -1) { return "String"; } else if (type.indexOf(TYPE_TIMESTAMP) > -1) { return "Date"; } else if (type.indexOf(TYPE_BIT) > -1) { return "Boolean"; } else if (type.indexOf(TYPE_DECIMAL) > -1) { return "BigDecimal"; } else if (type.indexOf(TYPE_BLOB) > -1) { return "byte[]"; } return null; } /** * 將欄位名轉換為實體類的屬性名 */ private String processField(String field) { StringBuilder sb = new StringBuilder(field.length()); String[] fields = field.split("_"); sb.append(fields[0]); for (int i = 1; i < fields.length; i++) { sb.append(upperCaseFirstLitter(fields[i].trim())); } return sb.toString(); } /** * 構建類上面的註釋 */ private void buildClassComment(BufferedWriter bw, String text) throws IOException { bw.newLine(); bw.newLine(); bw.write("/**"); bw.newLine(); bw.write(" * " + text); bw.newLine(); bw.write(" */"); } /** * 構建方法上面的註釋 */ private void buildMethodComment(BufferedWriter bw, String text) throws IOException { bw.newLine(); bw.write("\t/**" + text + "*/"); } /** * 生成實體類 */ private void buildEntityBean(List columns, List types, List comments, String tableComment) throws IOException { instanceFolder(BEAN_PATH); BufferedWriter bw = instanceBufferedWriter(BEAN_PATH, beanName + ".java"); writeBeanHead(tableComment, bw); writeBeanColumns(columns, types, comments, bw); // writeGetSetMethod(columns, types, bw); // writeGetByDto(columns, bw); writeEnd(bw); } /** * 寫類結尾處程式碼 */ private void writeEnd(BufferedWriter bw) throws IOException { bw.newLine(); bw.write("}"); bw.newLine(); bw.flush(); bw.close(); } /** * 寫根據dto生成實體類方法 */ private void writeGetByDto(List columns, BufferedWriter bw) throws IOException { bw.write("public static " + beanName + " get" + beanName + "(" + dtoName + " vo){"); bw.newLine(); bw.write("\t" + beanName + " " + lowerBeanName + " = new " + beanName + "();"); bw.newLine(); for (int i = 1; i < columns.size(); i++) { String fieldName = upperCaseFirstLitter(processField(columns.get(i))); bw.write("\t" + lowerBeanName + ".set" + fieldName + "(vo.get" + fieldName + "());"); bw.newLine(); } bw.write("\treturn " + lowerBeanName); bw.newLine(); bw.write("\t}"); bw.newLine(); } /** * 寫實體類的get,set方法 */ private void writeGetSetMethod(List columns, List types, BufferedWriter bw) throws IOException { String uppperField = null; String lowerField = null; String tempType = null; for (int i = 0; i < columns.size(); i++) { tempType = processType(types.get(i)); lowerField = processField(columns.get(i)); uppperField = upperCaseFirstLitter(lowerField); bw.newLine(); bw.write("\tpublic void set" + uppperField + "(" + tempType + " " + lowerField + "){"); bw.newLine(); bw.write("\t\tthis." + lowerField + " = " + lowerField + ";"); bw.newLine(); bw.write("\t}"); bw.newLine(); bw.newLine(); bw.write("\tpublic " + tempType + " get" + uppperField + "(){"); bw.newLine(); bw.write("\t\treturn this." + lowerField + ";"); bw.newLine(); bw.write("\t}"); bw.newLine(); } bw.newLine(); bw.newLine(); } /** * 寫實體類屬性程式碼 */ private void writeBeanColumns(List columns, List types, List comments, BufferedWriter bw) throws IOException { for (int i = 0; i < columns.size(); i++) { if (isNotEmpty(comments.get(i))) { bw.write("\t/**" + comments.get(i) + "*/"); bw.newLine(); } bw.write("\tprivate " + processType(types.get(i)) + " " + processField(columns.get(i)) + ";"); bw.newLine(); bw.newLine(); } bw.newLine(); } /** * 寫實體類頭部程式碼 */ private void writeBeanHead(String tableComment, BufferedWriter bw) throws IOException { bw.write("package " + BEAN_PACKAGE + ";"); bw.newLine(); bw.write("import java.io.Serializable;"); bw.newLine(); bw.write("import java.util.Date;"); bw.newLine(); buildClassComment(bw, tableComment + "實體類"); bw.newLine(); bw.write("public class " + beanName + " implements Serializable {"); bw.newLine(); bw.newLine(); } /** * 根據路徑建立檔案及輸出流 */ private BufferedWriter instanceBufferedWriter(String parent, String child) throws FileNotFoundException { File beanFile = new File(parent, child); return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile))); } /** * 根據路徑建立目錄 */ private void instanceFolder(String folderPath) { File folder = new File(folderPath); if (!folder.exists()) { folder.mkdir(); } } /** * 生成dto */ private void buildEntityDto(List columns, List types, List comments, String tableComment) throws IOException { instanceFolder(DTO_PATH); BufferedWriter bw = instanceBufferedWriter(DTO_PATH, dtoName + ".java"); writeDtoHead(tableComment, bw); writeDtoClumns(columns, types, comments, bw); writeEnd(bw); } /** * 寫DTO類屬性程式碼 */ private void writeDtoClumns(List columns, List types, List comments, BufferedWriter bw) throws IOException { String type = ""; for (int i = 0; i < columns.size(); i++) { if (isNotEmpty(comments.get(i))) { bw.write("\t/**" + comments.get(i) + "*/"); bw.newLine(); } if (types.get(i).indexOf(TYPE_DATE) > -1 || types.get(i).indexOf(TYPE_TIMESTAMP) > -1 ) { type = "char"; }else { type = types.get(i); } bw.write("\tprivate " + processType(type) + " " + processField(columns.get(i)) + ";"); bw.newLine(); bw.newLine(); } bw.newLine(); } /** * 寫DTO類頭部程式碼 */ private void writeDtoHead(String tableComment, BufferedWriter bw) throws IOException { bw.write("package " + DTO_PACKAGE + ";"); bw.newLine(); buildClassComment(bw, tableComment+"頁面顯示物件"); bw.newLine(); bw.write("public class " + dtoName + " {"); bw.newLine(); bw.newLine(); } /** * 構建方法程式碼 * * @param comment 方法註釋 * @param returnType 方法返回型別 * @param name 方法名 * @param param 方法引數 */ private void buildMethod(BufferedWriter bw, String comment, String returnType, String name, String param) throws IOException{ buildMethodComment(bw, comment); bw.newLine(); String result = MessageFormat.format("\t{0} {1}({2});", returnType, name, param); bw.write(result); bw.newLine(); } /** * 構建Dao檔案 */ private void buildMapper() throws IOException { instanceFolder(MAPPER_PATH); BufferedWriter bw = instanceBufferedWriter(MAPPER_PATH, mapperName + ".java"); writeMapperHead(bw); writeMethod(bw); writeEnd(bw); } /** * 寫Mapper及Service中方法程式碼 */ private void writeMethod(BufferedWriter bw) throws IOException { buildMethod(bw, "查詢(根據主鍵ID查詢", beanName, queryById, "String id"); buildMethod(bw, "刪除(根據主鍵ID刪除)", "int", delete, "String id"); buildMethod(bw, "新增", "int", save, beanName + " " + lowerBeanName); buildMethod(bw, "新增 (匹配有值的欄位)", "int", saveSelective, beanName + " " + lowerBeanName); buildMethod(bw, "修改", "int", update, beanName + " " + lowerBeanName); buildMethod(bw, "修改 (匹配有值的欄位)", "int", updateSelective, beanName + " " + lowerBeanName); if (useListMeathod) { buildMethod(bw, "根據條件分頁查詢", "List<" + beanName + "Dto>", queryPage, beanName + "Param param"); buildMethod(bw, "查詢總條數", "int", countTotalNum, beanName + "Param param"); } } /** * 寫Mapper類頭部程式碼 */ private void writeMapperHead(BufferedWriter bw) throws IOException { bw.write("package " + MAPPER_PACKAGE + ";"); bw.newLine(); bw.newLine(); bw.write("import " + BEAN_PACKAGE + "." + beanName + ";"); bw.newLine(); bw.write("import java.util.List;"); bw.newLine(); bw.write("import java.util.Map;"); bw.newLine(); bw.write("import org.apache.ibatis.annotations.Param;"); buildClassComment(bw, mapperName + "資料庫操作介面類"); bw.newLine(); bw.write("public interface " + mapperName + "{"); bw.newLine(); } /** * 構建Service檔案 */ private void buildServie() throws IOException { instanceFolder(SERVICE_PATH); BufferedWriter bw = instanceBufferedWriter(SERVICE_PATH, serviceName + ".java"); writeServiceHead(bw); writeMethod(bw); writeEnd(bw); } /** * 寫service介面頭部程式碼 */ private void writeServiceHead(BufferedWriter bw) throws IOException { bw.write("package " + SERVICE_PACKAGE + ";"); bw.newLine(); bw.newLine(); bw.write("import " + BEAN_PACKAGE + "." + beanName + ";"); bw.newLine(); bw.write("import java.util.List;"); bw.newLine(); bw.write("import java.util.Map;"); bw.newLine(); bw.write("import org.apache.ibatis.annotations.Param;"); buildClassComment(bw, serviceName + "資料庫操作介面類"); bw.newLine(); bw.write("public interface " + serviceName + " {"); bw.newLine(); } /** * 構建ServiceImpl檔案 */ private void buildServieImpl() throws IOException { instanceFolder(SERVICE_PATH); BufferedWriter bw = instanceBufferedWriter(SERVICE_PATH, serviceImplName + ".java"); writeServiceImplHead(bw); writeServieImplMethod(bw); writeEnd(bw); } /** * 寫serveImpl中的方法 */ private void writeServieImplMethod(BufferedWriter bw) throws IOException { String lowerMapperName = lowerCaseFirstLitter(mapperName); buildServiceImplMethod(bw, beanName, queryById, "String id", lowerMapperName); buildServiceImplMethod(bw, "int", delete, "String id", lowerMapperName); buildServiceImplMethod(bw, "int", save, beanName + " " + lowerBeanName, lowerMapperName); buildServiceImplMethod(bw, "int", saveSelective, beanName + " " + lowerBeanName, lowerMapperName); buildServiceImplMethod(bw, "int", update, beanName + " " + lowerBeanName, lowerMapperName); buildServiceImplMethod(bw, "int", updateSelective, beanName + " " + lowerBeanName, lowerMapperName); if(useListMeathod){ buildServiceImplMethod(bw, "List<" + beanName + "Dto>", queryPage, beanName + "Param param", lowerMapperName); buildServiceImplMethod(bw, "int", countTotalNum, beanName + "Param param", lowerMapperName); } } /** * 寫serveImpl中的方法 */ private void buildServiceImplMethod(BufferedWriter bw, String returnType, String name, String param, String lowerMapperName) throws IOException { bw.write("\
[email protected]"); bw.newLine(); bw.write(MessageFormat.format("\tpublic {0} {1}({2})", returnType, name, param)); bw.write("{"); bw.newLine(); bw.write(MessageFormat.format("\t\treturn {0}.{1}({2});", lowerMapperName, name.trim(), param.split(" ")[1])); bw.newLine(); bw.write("\t}"); bw.newLine(); bw.newLine(); } /** * 寫serviceImpl頭部程式碼 */ private void writeServiceImplHead(BufferedWriter bw) throws IOException { String lowerMapperName = lowerCaseFirstLitter(mapperName); bw.write("package " + SERVICEIMPL_PACKAGE + ";"); bw.newLine(); bw.newLine(); bw.write("import java.util.List;"); bw.newLine(); bw.write("import org.springframework.beans.factory.annotation.Autowired;"); bw.newLine(); bw.write("import org.springframework.stereotype.Service;"); bw.newLine(); bw.write("import " + BEAN_PACKAGE + "." + beanName + ";"); bw.newLine(); buildClassComment(bw, serviceImplName + "資料庫操作介面類"); bw.newLine(); bw.newLine(); bw.write("@Service"); bw.newLine(); bw.write("public class " + serviceImplName + " implements " + serviceName + " {"); bw.newLine(); bw.newLine(); bw.write("\[email protected]"); bw.newLine(); bw.write("\tprivate " + mapperName + " " + lowerMapperName + ";"); bw.newLine(); bw.newLine(); } /** * 構建實體類對映XML檔案 */ private void buildMapperXml(List columns, List types, List comments) throws IOException { instanceFolder(XML_PATH); BufferedWriter bw = instanceBufferedWriter(XML_PATH, mapperName + ".xml"); writeMapperXmlHead(bw); writeMapperXmlResultMap(columns, comments, bw); buildSQL(bw, columns, types); bw.write(""); bw.flush(); bw.close(); } /** * 寫Mappper.xml檔案對映程式碼 */ private void writeMapperXmlResultMap(List columns, List comments, BufferedWriter bw) throws IOException { bw.write("\t"); bw.newLine(); bw.write(MessageFormat.format("\t", lowerCaseFirstLitter(beanName), BEAN_PACKAGE, beanName)); bw.newLine(); bw.write("\t\t"); bw.newLine(); bw.write("\t\t"); bw.newLine(); int size = columns.size(); for (int i = 1; i < size; i++) { bw.write("\t\t"); bw.newLine(); bw.write("\t\t"); bw.newLine(); } bw.write("\t"); bw.newLine(); bw.newLine(); } /** * 寫Mapper.xml檔案頭部程式碼 */ private void writeMapperXmlHead(BufferedWriter bw) throws IOException { bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); bw.newLine(); bw.write(""-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">"); bw.newLine(); bw.write(""); bw.newLine(); bw.newLine(); } /** * 寫Mapper.xml增刪改查等語句 */ private void buildSQL(BufferedWriter bw, List columns, List types) throws IOException { writeClumnList(bw, columns); selectByPrimaryKey(bw, columns, types); insert(bw, columns); insertSelective(bw, columns); updateByPrimaryKey(bw, columns); updateByPrimaryKeySelective(bw, columns); deleteByPrimaryKey(bw, columns, types); } /** * 修改(匹配有值的欄位) */ private void updateByPrimaryKey(BufferedWriter bw, List columns) throws IOException { int size = columns.size(); bw.write("\t"); bw.newLine(); bw.write("\t"); bw.newLine(); bw.write("\t\t UPDATE " + tableName); bw.newLine(); bw.write("\t\t SET "); bw.newLine(); String tempField = null; for (int i = 1; i < size; i++) { tempField = processField(columns.get(i)); bw.write("\t\t\t " + columns.get(i) + " = #{" + tempField + "}"); if (i != size - 1) { bw.write(","); } bw.newLine(); } bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}"); bw.newLine(); bw.write("\t"); bw.newLine(); bw.newLine(); } /** * 修改(匹配有值的欄位) */ private void updateByPrimaryKeySelective(BufferedWriter bw, List columns) throws IOException { int size = columns.size(); bw.write("\t"); bw.newLine(); bw.write("\t"); bw.newLine(); bw.write("\t\t UPDATE " + tableName); bw.newLine(); bw.write(" \t\t "); bw.newLine(); String tempField = null; for (int i = 1; i < size; i++) { tempField = processField(columns.get(i)); bw.write("\t\t\t"); bw.newLine(); bw.write("\t\t\t\t " + columns.get(i) + " = #{" + tempField + "},"); bw.newLine(); bw.write("\t\t\t"); bw.newLine(); } bw.newLine(); bw.write(" \t\t "); bw.newLine(); bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}"); bw.newLine(); bw.write("\t"); bw.newLine(); bw.newLine(); } /** * insert方法(匹配有值的欄位) */ private void insertSelective(BufferedWriter bw, List columns) throws IOException { int size = columns.size(); bw.write("\t"); bw.newLine(); bw.write("\t"); bw.newLine(); bw.write("\t\t INSERT INTO " + tableName); bw.newLine(); bw.write("\t\t "); bw.newLine(); String tempField = null; for (int i = 0; i < size; i++) { tempField = processField(columns.get(i)); tempField = 0 == i ? "null" : tempField; bw.write("\t\t\t"); bw.newLine(); bw.write("\t\t\t\t " + columns.get(i) + ","); bw.newLine(); bw.write("\t\t\t"); bw.newLine(); } bw.newLine(); bw.write("\t\t "); bw.newLine(); bw.write("\t\t "); bw.newLine(); tempField = null; for (int i = 0; i < size; i++) { tempField = processField(columns.get(i)); bw.write("\t\t\t"); bw.newLine(); bw.write("\t\t\t\t #{" + tempField + "},"); bw.newLine(); bw.write("\t\t\t"); bw.newLine(); } bw.write("\t\t "); bw.newLine(); bw.write("\t"); bw.newLine(); bw.newLine(); } /** * 新增insert方法 */ private void insert(BufferedWriter bw, List columns) throws IOException { int size = columns.size(); bw.write("\t"); bw.newLine(); bw.write("\t"); bw.newLine(); selectKey(bw, columns); bw.write("\t\tINSERT INTO " + tableName + "("); bw.newLine(); bw.write("\t\t\t"); bw.newLine(); bw.write("\t\t)VALUES("); bw.newLine(); for (int i = 0; i < size; i++) { bw.write("\t\t\t"); bw.write("#{" + processField(columns.get(i)) + "}"); if (i != size - 1) { bw.write(","); } bw.newLine(); } bw.write("\t\t"); bw.write(") "); bw.newLine(); bw.write("\t"); bw.newLine(); bw.newLine(); } /** * 自動生成主鍵 * * * SELECT LAST_INSERT_ID() * */ private void selectKey(BufferedWriter bw, List columns) throws IOException { bw.write("\t\t"); bw.newLine(); bw.write("\t\t\tSELECT LAST_INSERT_ID()"); bw.newLine(); bw.write("\t\t"); bw.newLine(); } /** * 刪除(根據主鍵ID刪除) */ private void deleteByPrimaryKey(BufferedWriter bw, List columns, List types) throws IOException { bw.write("\t"); bw.newLine(); bw.write("\t"); bw.newLine(); bw.write("\t\t DELETE FROM " + tableName); bw.newLine(); bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}"); bw.newLine(); bw.write("\t"); bw.newLine(); bw.newLine(); } /** * 查詢(根據主鍵ID查詢) */ private void selectByPrimaryKey(BufferedWriter bw, List columns, List types) throws IOException { bw.write("\t"); bw.newLine(); bw.write(MessageFormat.format("\t"); bw.newLine(); bw.newLine(); } /** * 寫mapper.xml中所有列名的標籤 */ private void writeClumnList(BufferedWriter bw, List columns) throws IOException { int size = columns.size(); bw.write("\t"); bw.newLine(); bw.write("\t"); bw.newLine(); for (int i = 0; i < size; i++) { bw.write("\t\t" + columns.get(i)); if (i != size - 1) { bw.write(","); bw.newLine(); } } bw.newLine(); bw.write("\t"); bw.newLine(); bw.newLine(); bw.write("\t"); bw.newLine(); for (int i = 0; i < size; i++) { bw.write(MessageFormat.format("\t\t{0} AS {1}", columns.get(i), processField(columns.get(i)))); if (i != size - 1) { bw.write(","); bw.newLine(); } } bw.newLine(); bw.write("\t"); bw.newLine(); bw.newLine(); } /** * 獲取所有的資料庫表名及註釋 */ private Map getTableComment() throws SQLException { Map maps = new HashMap<>(); PreparedStatement pstate = conn.prepareStatement(showTablesInfo); ResultSet results = pstate.executeQuery(); while (results.next()) { String tableName = results.getString("NAME"); String comment = results.getString("COMMENT"); maps.put(tableName, comment); } return maps; } public static Boolean isEmpty(String str) { return null == str || "".equals(str); } public static Boolean isNotEmpty(String str) { return !isEmpty(str); } /** * 將字串首字母小寫 */ public static String lowerCaseFirstLitter(String str) { if(isEmpty(str)){ return ""; }else { return str.substring(0, 1).toLowerCase() + str.substring(1); } } /** * 將字串首字母大寫 */ public static String upperCaseFirstLitter(String str) { if(isEmpty(str)){ return ""; }else { return str.substring(0, 1).toUpperCase() + str.substring(1); } } /** * 根據某一個表生成實體類,dto,service,mapper,mapper.xml */ private void generateByTable(Map tableComments, String table) throws SQLException, IOException { columns.clear(); types.clear(); comments.clear(); PreparedStatement pstate = conn.prepareStatement(showFields + table); ResultSet results = pstate.executeQuery(); while (results.next()) { columns.add(results.getString("FIELD")); types.add(results.getString("TYPE")); comments.add(results.getString("COMMENT")); } initNameByTable(table); String tableComment = tableComments.get(table); buildEntityBean(columns, types, comments, tableComment); buildEntityDto(columns, types, comments, tableComment); buildMapper(); buildMapperXml(columns, types, comments); buildServie(); buildServieImpl(); } /** * 獲取所有的表資訊並迴圈生成相應檔案 */ public void generate() throws ClassNotFoundException, SQLException, IOException { initConnection(); Map tableComments = getTableComment(); if(isNotEmpty(TABLE_NAME)){ generateByTable(tableComments, TABLE_NAME); }else { List tables = getTables(); for (String table : tables) { generateByTable(tableComments, table); } } conn.close(); } public static void main(String[] args) { try { Runtime runtime = Runtime.getRuntime(); mkdirs(runtime); new EntityUtil().generate(); // 自動開啟生成檔案的目錄 runtime.exec("cmd /c start explorer " + PACKAGEPATH); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }