1. Create the jdbc.properties configuration file

jdbc.driver = com.mysql.cj.jdbc.Driver jdbc.user = root jdbc.password = 1234 jdbc.url = jdbc:mysql://localhost:3306/jiabin? useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&auto Reconnect=true&allowPublicKeyRetrieval=true # Dbc.database = jiabin # JDBc.packagename = Src.main.java.com.hsn.test # guide package path JDBC. Package = com. HSN. TestCopy the code

2. Generate javaBean

public class TableToBean { public static void main(String[] args) throws Exception { // 1. Database connection class.forname (util.getPropertyValue ("jdbc.driver")); Connection connection = DriverManager.getConnection(Util.getPropertyValue("jdbc.url"), Util.getPropertyValue("jdbc.user"), Util.getPropertyValue("jdbc.password")); DatabaseMetaData metaData = connection.getMetaData(); ResultSet tables = metadata. getTables(util.getPropertyValue ("jdbc.database"), null, null, null); String packageName = util.getPropertyValue (" jdbc.packagename "); String dir = Util.createDir(packageName); CreateJavaBean util. createJavaBean(metaData, tables, dir); }}Copy the code

3. The tools

 public class Util {    public final static Map<String, String> SQL_TYPE2JAVA_TYPE = new HashMap<>(); 
   public final static Map<String, String> IMPORT_PACK_MAP = new HashMap<>(); 
   // 需要维护字段数据类型对应java数据类型   
 static {        SQL_TYPE2JAVA_TYPE.put("INT UNSIGNED", "Integer");    
    SQL_TYPE2JAVA_TYPE.put("VARCHAR", "String");      
   SQL_TYPE2JAVA_TYPE.put("TIMESTAMP", "Date");    
    SQL_TYPE2JAVA_TYPE.put("INT", "Integer");      
    SQL_TYPE2JAVA_TYPE.put("TINYINT", "Byte");    
    SQL_TYPE2JAVA_TYPE.put("DATETIME", "Date");   
     SQL_TYPE2JAVA_TYPE.put("CHAR", "String");    
    SQL_TYPE2JAVA_TYPE.put("TEXT","String");       
  SQL_TYPE2JAVA_TYPE.put("LONGTEXT","String");     
   IMPORT_PACK_MAP.put("DATETIME", "import java.util.Date;");      
  IMPORT_PACK_MAP.put("TIMESTAMP", "import java.util.Date;");  
  }  

 
 /**     * 获取配置文件值     *     * @param key     * @return     * @throws IOException     */  
  public static String getPropertyValue(String key) throws IOException {   
      InputStream in = TableToBean.class.getClassLoader().getResourceAsStream("jdbc.properties"); 
       Properties p = new Properties();   
      p.load(in);     
    return p.getProperty(key);    
}
   
 /**     * 创建包     *     * @param packageName     * @return     */   
 public static String createDir(String packageName)  {     
   String path = null;       
 try {          
  StringBuilder rootPath = new StringBuilder(new File("").getCanonicalPath() + File.separator); 
          String[] fileNames = packageName.split("\\.");   
         for (String string : fileNames) {      
         rootPath.append(File.separator).append(string);       
     }    
       File file = new File(rootPath.toString());       
     file.mkdirs(); // 创建多层目录     
      path = file.getCanonicalPath();    
       System.out.println("生成路径成功");       
 } catch (Exception e) {       
     e.printStackTrace();          
  System.err.println("生成失败");     
   }       
 return path;    
}    

/**     * 根据数据表名替换成类名     *     * @param className     * @return     */  
  public static String generateClassName(String className) {  
      StringBuilder stringBuilder = new StringBuilder();      
  String[] s = className.split("_");      
  for (String value : s) {     
       stringBuilder.append(value.substring(0, 1).toUpperCase()).append(value.substring(1));
        }     
   return stringBuilder.toString();   
 }   
 
/**     * 根据数据表名替换成字段名     *     * @param columName     * @return     */  
  public static String generateColumName(String columName) {    
    StringBuilder stringBuilder = new StringBuilder();   
     String[] s = columName.split("_");     
   for (int i = 0; i < s.length; i++) {        
    if (i == 0) {          
      stringBuilder.append(s[i].substring(i, i + 1).toLowerCase()).append(s[i].substring(i + 1));            } else {                stringBuilder.append(s[i].substring(0, 1).toUpperCase()).append(s[i].substring(1));         
   }    
    }   
     return stringBuilder.toString();   
 }   

 /**     * 将生成的PO写到类路径下     *     * @param path     * @param clazzContent     */ 
   public static void writeClazz(String path, String clazzContent) {   
     FileOutputStream fileOutputStream = null;       
 try {    
        fileOutputStream = new FileOutputStream(new File(path));     
       fileOutputStream.write(clazzContent.getBytes());    
        fileOutputStream.close();    
    } catch (Exception e) {     
       e.printStackTrace();    
    } finally {       
     if (fileOutputStream != null) {          
      try {           
         fileOutputStream.close();         
       } catch (IOException e) {        
            e.printStackTrace();         
       }          
  }       
 }   
 }  

  /**     * 创建javaBean     *     * @param metaData     * @param tables     * @param dir     * @throws Exception     */ 
   public static void createJavaBean(DatabaseMetaData metaData, ResultSet tables, String dir) throws Exception { 
       while (tables.next()) {            //  System.out.println(tables.getString(1)); // 库名    
        //   System.out.println(tables.getString(2)); // null            String tableName = tables.getString(3);// 表名    
        ResultSet columns = metaData.getColumns(Util.getPropertyValue("jdbc.database"), null, tableName, null);         
   Map<String, String> dataMap = new HashMap<>();   
         while (columns.next()) {            
    String column_name = columns.getString("COLUMN_NAME");// 字段名         
       String type_name = columns.getString("TYPE_NAME");// 字段类型     
           dataMap.put(column_name, type_name);         
   }    
  
      // 4.构建类:a、导包 b、构建类信息c、构建属性 d、封装属性 e、创建包 f、创建 JAVA BEAN      
      StringBuilder clazz = new StringBuilder();     
       clazz.append("package ").append(Util.getPropertyValue("jdbc.package")).append(";").append("\n");    
        Set<Map.Entry<String, String>> entries = dataMap.entrySet();        
    // 导包            for (Map.Entry<String, String> entry : entries) {     
           String dataType = Util.IMPORT_PACK_MAP.get(entry.getValue());          
      if (dataType != null && !clazz.toString().contains("import java.util.Date;")) {    
                clazz.append(dataType).append("\n\n");      
          }   
         }   
         clazz.append("public class ").append(Util.generateClassName(tableName)).append(" {").append("\n\n");            // 构建字段属性    
        for (Map.Entry<String, String> entry : entries) {                String dataType = Util.SQL_TYPE2JAVA_TYPE.get(entry.getValue());   
             if (dataType != null) {                    clazz.append("\t").append("private ").append(dataType).append(" ").append(Util.generateColumName(entry.getKey())).append(";" + "\n\n");      
          }        
    }       
     // getter 与 setter        
    for (Map.Entry<String, String> entry : entries) {       
         clazz.append("\t" + "public void set").append(Util.generateClassName(entry.getKey())).append("(").append(Util.SQL_TYPE2JAVA_TYPE.get(entry.getValue())).append(" ").append(Util.generateColumName(entry.getKey())).append(") {").append("\n").append("\t\t").append("this.").append(Util.generateColumName(entry.getKey())).append(" ").append("= ").append(Util.generateColumName(entry.getKey())).append(";").append("\n").append("\t").append("}").append("\n\n");      
      }      
      for (Map.Entry<String, String> entry : entries) {     
           clazz.append("\t" + "private ").append(Util.SQL_TYPE2JAVA_TYPE.get(entry.getValue())).append(" get").append(Util.generateClassName(entry.getKey())).append("() {").append("\n").append("\t\t").append("return ").append(Util.generateColumName(entry.getKey())).append(";").append("\n").append("\t").append("}").append("\n\n");          
  }       
     clazz.append("}");       
     Util.writeClazz(dir + File.separator + Util.generateClassName(tableName) + ".java", clazz.toString());  
      }   
 }
}
Copy the code

4. Precautions

There are static code blocks in the tool class that need to maintain the field data types corresponding to the Java data types. It does not take into account all database data types. If necessary, you can manually improve it

5. Effect display

Interested partners can start to try ah