工做中,老是遇到編寫javabean的工做,每次都寫得噁心,並且表和字段是下劃線的,例如:created_date;而javabean是駝峯的,例如:createdDate。那麼,就須要以下的工具類了。java
/** * 從數據庫表反射出實體類,自動生成實體類 * @author lqx * */ public class GenEntityMysql { private String packageOutPath = "com.funsmart.model";//指定實體生成所在包的路徑 private String namespacePrefix= "com.funsmart.dao"; //指定mapper文件的命名空間 private String mapperOutPath= "com.funsmart.mapper"; //指定mapper文件的存放路徑 private String authorName = "lqx";//做者名字 private String tablename = "";//表名 private String className = "";//類名 private String[] colnames; // 列名數組 private String[] colTypes; //列名類型數組 private int[] colSizes; //列名大小數組 private boolean f_util = false; // 是否須要導入包java.util.* private boolean f_sql = false; // 是否須要導入包java.sql.* private boolean f_jpa = false; // 是否須要生成基於註解的JPA實體對象 //數據庫鏈接 private static final String URL ="jdbc:mysql://127.0.0.1:3306/demo"; private static final String NAME = "root"; private static final String PASS = "root"; private static final String DRIVER ="com.mysql.jdbc.Driver"; /* * 構造函數 */ public GenEntityMysql(){ } /** * 生成全部的錶轉成JavaBean */ public void genAllTablToBean(){ List<String> list=getTableName(); for(int p=0;p<list.size();p++){ tablename=list.get(p); className = getClassName(tablename); //建立鏈接 Connection con; //查要生成實體類的表 String sql = "select * from " + tablename; PreparedStatement pStemt = null; try { try { Class.forName(DRIVER); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } con = DriverManager.getConnection(URL,NAME,PASS); pStemt = con.prepareStatement(sql); ResultSetMetaData rsmd = pStemt.getMetaData(); int size = rsmd.getColumnCount(); //統計列 colnames = new String[size]; colTypes = new String[size]; colSizes = new int[size]; for (int i = 0; i < size; i++) { colnames[i] = rsmd.getColumnName(i + 1); colTypes[i] = rsmd.getColumnTypeName(i + 1); if(colTypes[i].equalsIgnoreCase("datetime")){ f_util = true; } if(colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")){ f_sql = true; } colSizes[i] = rsmd.getColumnDisplaySize(i + 1); } String content = parse(colnames,colTypes,colSizes); try { File directory = new File(""); String outputPath = directory.getAbsolutePath()+ "/src/main/java/"+this.packageOutPath.replace(".", "/")+"/"+initcap(className) + ".java"; FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); pw.println(content); pw.flush(); pw.close(); } catch (IOException e) { e.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } finally{ // try { // con.close(); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } } System.out.println("生成完畢!"); } /** * 單表 * 將錶轉成JavaBean */ public void genTablToBean(String tableName){ // List<String> list=getTableName(); // for(int p=0;p<list.size();p++){ tablename=tableName; className = getClassName(tablename); //建立鏈接 Connection con; //查要生成實體類的表 String sql = "select * from " + tablename; PreparedStatement pStemt = null; try { try { Class.forName(DRIVER); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } con = DriverManager.getConnection(URL,NAME,PASS); pStemt = con.prepareStatement(sql); ResultSetMetaData rsmd = pStemt.getMetaData(); int size = rsmd.getColumnCount(); //統計列 colnames = new String[size]; colTypes = new String[size]; colSizes = new int[size]; for (int i = 0; i < size; i++) { colnames[i] = rsmd.getColumnName(i + 1); colTypes[i] = rsmd.getColumnTypeName(i + 1); if(colTypes[i].equalsIgnoreCase("datetime")){ f_util = true; } if(colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")){ f_sql = true; } colSizes[i] = rsmd.getColumnDisplaySize(i + 1); } String content = parse(colnames,colTypes,colSizes); try { File directory = new File(""); String outputPath = directory.getAbsolutePath()+ "/src/main/java/"+this.packageOutPath.replace(".", "/")+"/"+initcap(className) + ".java"; FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); pw.println(content); pw.flush(); pw.close(); } catch (IOException e) { e.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } finally{ // try { // con.close(); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } // } System.out.println("生成完畢!"); } /** * Java方法 獲得當前數據庫下全部的表名 * @param con */ private List<String> getTableName() { List<String> list=new ArrayList<String>(); try { DatabaseMetaData meta = DriverManager.getConnection(URL,NAME,PASS).getMetaData(); ResultSet rs = meta.getTables(null, null, null,new String[]{"TABLE"}); while (rs.next()) { String tableName = rs.getString(3); // 獲取表名 if(StringUtils.isNotBlank(tableName)){ list.add(tableName); } } }catch(Exception e){ e.printStackTrace(); } return list; } /** * 將表名轉爲類名 * @param tableName * @return */ private String getClassName(String tableName){ // 將表名前綴t_去掉 tableName = StringUtils.removeStart(tableName, "t_"); tableName = FieldUtils.camelName(tableName); return tableName; } /** * 功能:生成實體類主體代碼 * @param colnames * @param colTypes * @param colSizes * @return */ private String parse(String[] colnames, String[] colTypes, int[] colSizes) { StringBuffer sb = new StringBuffer(); sb.append("package " + this.packageOutPath + ";\r\n"); sb.append("\r\n"); //判斷是否導入工具包 if(f_util){ sb.append("import java.util.Date;\r\n"); } if(f_sql){ sb.append("import java.sql.*;\r\n"); } //jpa if(f_jpa){ sb.append("import javax.persistence.Entity;\r\n"); sb.append("import javax.persistence.GeneratedValue;\r\n"); sb.append("import javax.persistence.GenerationType;\r\n"); sb.append("import javax.persistence.Id;\r\n\r\n"); } //註釋部分 sb.append("/**\r\n"); sb.append(" * "+className+" 實體類\r\n"); sb.append(" * "+new Date()+"\r\n"); sb.append(" * @"+this.authorName+"\r\n"); sb.append(" */ \r\n"); if(f_jpa){ sb.append("@Entity\r\n"); } //實體部分 sb.append("public class " + initcap(className) + "{\r\n\r\n"); processAllAttrs(sb);//屬性 processAllMethod(sb);//get set方法 sb.append("}\r\n"); //System.out.println(sb.toString()); return sb.toString(); } /** * 功能:生成全部屬性 * @param sb */ private void processAllAttrs(StringBuffer sb) { for (int i = 0; i < colnames.length; i++) { String fieldStr = colnames[i]; if(fieldStr.indexOf("_") != -1){ fieldStr = FieldUtils.camelName(fieldStr); } sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + fieldStr + ";\r\n"); } sb.append("\r\n"); } /** * 功能:生成全部方法 * @param sb */ private void processAllMethod(StringBuffer sb) { for (int i = 0; i < colnames.length; i++) { String fieldStr = colnames[i]; if(fieldStr.indexOf("_") != -1){ fieldStr = FieldUtils.camelName(fieldStr); } if(f_jpa){ if(i==0){ sb.append("\t@Id\r\n"); sb.append("\t@GeneratedValue(strategy = GenerationType.AUTO)\r\n"); sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(fieldStr) + "(){\r\n"); }else{ sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(fieldStr) + "(){\r\n"); } }else{ sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(fieldStr) + "(){\r\n"); } sb.append("\t\treturn " + fieldStr + ";\r\n"); sb.append("\t}\r\n\r\n"); sb.append("\tpublic void set" + initcap(fieldStr) + "(" + sqlType2JavaType(colTypes[i]) + " " + fieldStr + "){\r\n"); sb.append("\t\tthis." + fieldStr + "=" + fieldStr + ";\r\n"); sb.append("\t}\r\n\r\n"); } } /** * 功能:將輸入字符串的首字母改爲大寫 * @param str * @return */ private String initcap(String str) { char[] ch = str.toCharArray(); if(ch[0] >= 'a' && ch[0] <= 'z'){ ch[0] = (char)(ch[0] - 32); } return new String(ch); } /** * 功能:得到列的數據類型 * @param sqlType * @return */ private String sqlType2JavaType(String sqlType) { if(sqlType.equalsIgnoreCase("bit")){ return "boolean"; }else if(sqlType.equalsIgnoreCase("tinyint")){ return "int"; }else if(sqlType.equalsIgnoreCase("smallint")){ return "int"; }else if(sqlType.equalsIgnoreCase("int")||sqlType.equalsIgnoreCase("INT UNSIGNED")){ //INT UNSIGNED無符號整形 return "int"; }else if(sqlType.equalsIgnoreCase("bigint")){ return "long"; }else if(sqlType.equalsIgnoreCase("float")){ return "float"; }else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric") || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney")){ return "double"; }else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("text")){ return "String"; }else if(sqlType.equalsIgnoreCase("datetime")){ return "Date"; }else if(sqlType.equalsIgnoreCase("image")){ return "Blod"; } return null; } /** * 出口 * TODO * @param args */ public static void main(String[] args) { new GenEntityMysql().genTablToBean("t_city"); } }
下劃線轉駝峯的工具類mysql
/** * 字段的工具類 * 將駝峯轉下劃線 * 將下劃線轉駝峯 * User: linqx * Time: 2015-07-22 22:58 */ public class FieldUtils { /** * 將駝峯式命名的字符串轉換爲下劃線大寫方式。若是轉換前的駝峯式命名的字符串爲空,則返回空字符串。</br> * 例如:HelloWorld->HELLO_WORLD * @param name 轉換前的駝峯式命名的字符串 * @return 轉換後下劃線大寫方式命名的字符串 */ public static String underscoreName(String name) { StringBuilder result = new StringBuilder(); if (name != null && name.length() > 0) { // 將第一個字符處理成大寫 result.append(name.substring(0, 1).toUpperCase()); // 循環處理其他字符 for (int i = 1; i < name.length(); i++) { String s = name.substring(i, i + 1); // 在大寫字母前添加下劃線 if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) { result.append("_"); } // 其餘字符直接轉成大寫 result.append(s.toUpperCase()); } } return result.toString(); } /** * 將下劃線大寫方式命名的字符串轉換爲駝峯式。若是轉換前的下劃線大寫方式命名的字符串爲空,則返回空字符串。</br> * 例如:HELLO_WORLD->HelloWorld * @param name 轉換前的下劃線大寫方式命名的字符串 * @return 轉換後的駝峯式命名的字符串 */ public static String camelName(String name) { StringBuilder result = new StringBuilder(); // 快速檢查 if (name == null || name.isEmpty()) { // 不必轉換 return ""; } else if (!name.contains("_")) { // 不含下劃線,僅將首字母小寫 return name.substring(0, 1).toLowerCase() + name.substring(1); } // 用下劃線將原始字符串分割 String camels[] = name.split("_"); for (String camel : camels) { // 跳過原始字符串中開頭、結尾的下換線或雙重下劃線 if (camel.isEmpty()) { continue; } // 處理真正的駝峯片斷 if (result.length() == 0) { // 第一個駝峯片斷,所有字母都小寫 result.append(camel.toLowerCase()); } else { // 其餘的駝峯片斷,首字母大寫 result.append(camel.substring(0, 1).toUpperCase()); result.append(camel.substring(1).toLowerCase()); } } return result.toString(); } }
就是這樣啦。git
java學習和交流羣:22160972sql