2016-11-25 21 views
2

我創建一個數據庫寫入數據的程序。我爲每個表創建了類,我希望這個類能夠創建自己的INSERT語句。由於成員變量將成爲數據庫的列,我認爲用obj.getClass().getDeclaredFields()來抓取它們並將它們寫入INSERT語句是個不錯的主意。我不想複製代碼,所以我創建了一個具有buildSqlInsertQuery()的Table類,並用它來擴展其他類。生成某些實例變量的列表

問題是我可能在這些類中需要其他實例變量(例如tableName),我不想成爲INSERT語句的一部分。我也想分配值列,所以我不認爲我可以只是把它們放入數組,而無需複製(所以如果我添加了一個專欄中,我還需要將其添加到陣列)。

這裏是我的那一刻,這將包括在INSERT查詢的表名:

Table.java

public class Table { 
    public String buildSqlInsertQuery(Object obj, String tableName) { 
     Field[] fields = obj.getClass().getDeclaredFields(); 
     String[] fieldNames = new String[fields.length]; 
     String[] placeholders = new String[fields.length]; 
     String placeholder = "?"; 

     for (int x = 0; x < fields.length; x += 1) { 
      fieldNames[x] = fields[x].getName(); 
      placeholders[x] = placeholder; 
     } 

     return joinInsertQuery(tableName, fieldNames, placeholders); 
    } 

    private String joinInsertQuery(String tableName, String[] fieldNames, String[] placeholders) { 
     String query = "INSERT INTO " + tableName + " ("; 
     query += StringUtils.join(fieldNames, ","); 
     query += ") VALUES ("; 
     query += StringUtils.join(placeholders, ","); 
     query += ")"; 

     return query; 
    } 
} 

Addresses.java

public class Addresses extends Table { 
    private final static String tableName = "Addresses"; 
    public String idCustomers; 
    public String address1; 
    public String address2; 
    public String address3; 
    public String city; 
    public String state; 
    public String zip; 
    public String country; 

    public Addresses() { 
     System.out.println(buildSqlInsertQuery(this, this.tableName)); 
    } 
} 

有沒有我可以標記某些實例變量應該考慮的列(如與註釋)或我要對這個完全錯誤的方式?

+1

你知道存在多個庫來做這個嗎?無論如何,你可以使用字段的'transient'改性劑和[檢查這個在運行時(https://docs.oracle.com/javase/tutorial/reflect/member/fieldModifiers.html)。此外,'JPA'規範爲此提供了[註釋](https://docs.oracle.com/javaee/7/api/javax/persistence/Transient.html)。 – PeterMmm

回答

2

的一種方式,你所提到的,就是用標註標識實例變量作爲table name。只要定義的註釋,因爲這:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.FIELD) 
public @interface TableAnnotation { 

} 

而且具有表的名稱與該領域的註解:

public class Addresses { 

@TableAnnotation 
private String tableName = "Addresses"; 
public String idCustomers; 
public String address1; 
... 
} 

現在,在您Table類,使用反射(你已經這樣做)到用這個特別的註解來解釋這個領域:

if(field.isAnnotationPresent(TableAnnotation.class)){ 
     System.out.println("This field " + field.getName() + " is the name of table"); 
} 
+0

這真的很有幫助,謝謝。 – SBmore

+0

@SBmore歡迎您! –

1

你可以創建你自己的註解和註釋你的字段。 然後,您可以找到帶反射的註釋字段。

for (Field field : c.getDeclaredFields()) { 
    if (field.isAnnotationPresent(Annotation)) { 
    set.add(field); 
    } 
}