java工具類–自動將資料庫表產生javabean

來源:互聯網
上載者:User

標籤:

最近和資料庫的表打交道挺多的,因為暫時做的是介面活。

在這過程中發現要把錶轉換成對應的javabean類型,欄位少的表還行,如果不小心碰到幾十個欄位的他媽的寫起來就有點麻煩了,萬一碰到幾百個的呢,那不是要崩潰。

於是想寫個工具類,自動產生javabean。

先說下思路:

1.讀取資料庫表,擷取裡面的欄位名。

準備串連資料庫的驅動包,這裡只是針對了oracle資料庫和mysql資料庫

2.構建一個stringBuffer字串,用來產生我們需要的類。

3.寫入檔案

要求具備相應的檔案流知識。

好了,準備工作就這些,下面附上代碼,

 

 

package com.tool;
/*
 * 給出資料庫JAR包,資料庫連結路徑,資料庫資料表空間名,資料庫名,資料庫密碼,表名
 *可以提取出來建立表屬性的javaBean檔案,並且提供標準的get,set方法。
 * 此程式將所有欄位和資料提取出來定義為String類型,如有別的需要可以提取表中欄位的類型和別的表資訊,自動產生
 * java檔案
 * \t 表示 空格
 * \r 表示換行 等價於 \n
 * ResultSetMetaData 關鍵
 * */
import java.io.BufferedWriter;
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.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
 
public class SqlToBean {
 private Connection conn = null;    //儲存連結路徑
 private Statement stmt = null;     //建立串連
 private ResultSetMetaData meta = null;  //儲存表屬性資訊
 private ResultSet rs = null;  //查詢結果集
 private OutputStreamWriter osw = null;
 private BufferedWriter bw = null;
 private FileOutputStream fos = null;
 private static StringBuffer coding = new StringBuffer();  //字串緩衝區
 private String driver = null;    //資料庫包名
 private String url = null;          //路徑名
 private String table = null;        //資料表空間名
 private String password = null;     //密碼
 private String tableName = null;    //表名
 
 public SqlToBean(String driver, String url, String table, String password, String tableName) {
  this.driver = driver;
  this.url = url;
  this.table = table;
  this.password = password;
  this.tableName = tableName;
 }
 
 private String getCoding(StringBuffer code) {
  return code.toString();
 }
 
 private StringBuffer createGenerate(String property) {
  String prop = property.toLowerCase();
  coding.append("\r \t private String " + prop + ";");
  return coding;
 }
 
 private StringBuffer createMethod(String[] str){
  for(int i=0;i<str.length;i++){
   //str[i].charAt(0) - 32)轉成大寫   思路
   str[i] = str[i].toLowerCase();
   coding.append("\r \t public void set" + (char)(str[i].charAt(0) - 32)+ str[i].substring(1)+"(String " + str[i] +"){");
   coding.append("\r \t\t this."+str[i] + "=" + str[i] + ";");
   coding.append("\r \t }");
   coding.append("\r \t public String get" + (char)(str[i].charAt(0) - 32)+ str[i].substring(1)+"(){");
   coding.append("\r \t\t return this."+str[i] +  ";");
   coding.append("\r \t }\n");
  }
  return coding;
 }
 /*
  * 關閉與資料庫的所有連結
  * */
 private void destroy() {
  try {
   if(conn != null){
    conn.close();
    conn = null;
   }
   if(stmt != null){
    stmt.close();
    stmt = null;
   }
   if(rs != null){
    rs.close();
    rs = null;
   }
 
   if(bw != null){
    bw.close();
    bw = null;
   }
   if(fos != null) {
    fos.close();
    fos = null;
   }
   if(osw != null) {
    osw.close();
    osw = null;
   }
 
  } catch (SQLException e) {
   e.printStackTrace();
  }  catch (IOException e) {
   e.printStackTrace();
  }
 }
 /*
  * 資料庫連接發生異常就關閉連結
  * */
 private  void connect () {
  try {
   Class.forName(driver);
   conn = DriverManager.getConnection(url,table,password);
   stmt = conn.createStatement();
 
   rs = stmt.executeQuery("select  * from " + tableName ); //查詢下確定結果集是那個表的
   meta = rs.getMetaData();                         //調用結果集的記錄表資訊的方法
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
   try {
    if(conn != null){
     conn.close();
     conn = null;
    }
    if(stmt != null){
     stmt.close();
     stmt = null;
    }
    if(rs != null){
     rs.close();
     rs = null;
    }
   } catch (SQLException e1) {
    e.printStackTrace();
   }
  }  catch (SQLException e) {
   e.printStackTrace();
   try {
    if(conn != null){
     conn.close();
     conn = null;
    }
    if(stmt != null){
     stmt.close();
     stmt = null;
    }
    if(rs != null){
     rs.close();
     rs = null;
    }
   } catch (SQLException e1) {
    e.printStackTrace();
   }
  }
 
 }
 
 private String[] getColumenName() {
  /*得到表的所有列名以字串數組的形式返回
   * */
  int count;
  String[] str = null;
  try {
   count = meta.getColumnCount();
   String[] strColumenName = new String[count];
   for(int i = 1;i <= count; i++) {
    strColumenName[i-1] = meta.getColumnName(i);
   }
   str = strColumenName;
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return str;
 }
 /**
  * 寫入指定的檔案中
  * @param message
  */
 private void writeData(String message,String className) {
  String file = "C:\\"+className+".java";
  try {
   fos = new FileOutputStream(file);
   osw = new OutputStreamWriter(fos);
   bw = new BufferedWriter(osw);
   bw.write(message);
   bw.flush();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 
 }
 
 public StringBuffer createClassName(String className){
  coding.append("public class " + className + "{\n");
  return coding;
 }
 
 public static void main(String[] args) {
  String className = "Hellow";
  //SqlToBean sqlToBean = new SqlToBean("oracle.jdbc.driver.OracleDriver","jdbc:oracle:thin:@192.168.3.11:1521:orcl","mamibon","mamibon","my_standard_data2");
  SqlToBean sqlToBean = new SqlToBean("org.gjt.mm.mysql.Driver","jdbc:mysql://117.79.84.144:3306/wordpress","wangjun","wangjun123","wp_users");
  //串連資料庫
  sqlToBean.connect();
  sqlToBean.createClassName(className);
  //擷取表的欄位
  String[] str ;
  str = sqlToBean.getColumenName();
  for(int i = 0;i<str.length ;i++) {
   sqlToBean.createGenerate(str[i]);
  }
  coding.append("\n");
  sqlToBean.createMethod(str);
  coding.append("\n}");
  //寫入檔案
  sqlToBean.writeData(sqlToBean.getCoding(coding),className);
  sqlToBean.destroy();
 
  System.out.println("如果覺得這工具類不錯,請關注我們的網站:http://www.itbuluoge.com,期待你的入住,程式員俱樂部,為您提供更多的協助!");
  System.out.println("如果覺得這工具類不錯,請關注我們的網站:http://www.itbuluoge.com,期待你的入住,程式員俱樂部,為您提供更多的協助!");
 }
 
}

java工具類–自動將資料庫表產生javabean

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.