2017-01-23 61 views
1

我有一個看起來像一個XML輸入文件:讀取XML和創建多個表

<mbean className="OperatingSystem"> 
    <attribute> 
     <attributeName>Arch</attributeName> 
     <formatter>STRING</formatter> 
    </attribute> 
    <attribute> 
     <attributeName>ProcessCpuLoad</attributeName> 
     <formatType>PERCENT</formatType> 
    </attribute> 
</mbean> 

我已經創建了一個名爲 'Mbean的',看起來像POJO:

@XmlRootElement(name = "mbean") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Mbean 
{ 
    @XmlElement(name = "attribute") 
    private List<Attribute> attributes = null; 

    @XmlAttribute(name = "className") 
    private String className; 

    public String getClassName() { 
     return className; 
    } 
} 

我可以成功解開我的XML文件到這個POJO中,我的應用程序可以使用這個對象作爲nee DED。這個輸入文件告訴我我需要從一個特定的MBean中獲取的信息。有沒有辦法根據XML文件創建多個表,例如,當我提取所述信息時,我可以將該信息存儲到所述表結構中,然後使用JDBC在我的H2數據庫上創建SQL表?

例如,我想創建一個看起來像表:

+------------------------+ 
|  MBeans   |  
+------+-----------------+ 
| ID | MBeanName  | 
+------+-----------------+ 
| 1 | OperatingSystem | 
+------+-----------------+ 

+--------------------------------+ 
|  Attributes    | 
+------+--------+----------------+ 
| ID | MbeanId| AttributeName | 
+------+--------+----------------+ 
| 1 | 1 | Arch   | 
+------+--------+----------------+ 
| 2 | 1 | ProcessCpuLoad | 
+------+--------+----------------+ 

+------------------------------------+ 
|  OperatingSystem.Arch  | 
+------+--------+------------+-------+ 
| ID | MbeanId| AttributeId| Value | 
+------+--------+------------+-------+ 
| 1 | 1 | 1  | amd64 | 
+------+--------+------------+-------+ 
| 2 | 1 | 1  | amd64 | 
+------+--------+------------+-------+ 

+------------------------------------+ 
| OperatingSystem.ProcessCpuLoad  | 
+------+--------+------------+-------+ 
| ID | MbeanId| AttributeId| Value | 
+------+--------+------------+-------+ 
| 1 | 1 | 2  | 0.009 | 
+------+--------+------------+-------+ 
| 2 | 1 | 2  | 0.0691| 
+------+--------+------------+-------+ 

回答

1

我會先:

  • 的方法映射className到表名public String getTableName(String className)
  • 的方法映射attributeName成clomun名稱public String getColumnName(String attributeName)
  • 映射方法formatTypeformatter到數據庫類型public String getType(String formatType)

然後

public void createTable(Mbean bean) throws SQLException{ 
    String sql = getCreateTable(bean); 
    // execute SQL using JDBC... 
} 

private String getCreateTable(Mbean bean) { 
    String sqlStart = "CREATE TABLE " + getTableName(bean.getClassName()) + " (" ; 
    return bean.getAttributes().stream() 
     .map(attribute -> mapToColumn(attribute)) 
     .collect(Collectors.joining(", ", sqlStart, ")"); // what about primary key? 
} 

private String mapToColumn(Attribute a) { 
    return getColumnName(a.getName()) + " " + getType(/*it depends*/); 
} 
+0

謝謝!雖然我沒有按照你的建議來實施,但你的解決方案給了我一個想法。我創建了一個名爲Table with Rows的對象,此表的列爲{「ID」,「MbeanID」,「AttributeID」,「Value」}。然後以受getCreateTable()啓發的方式將此對象傳遞給名爲update的方法,該方法可以創建必要的sql表(如果它們尚不存在),或使用「insert」語句更新現有表。 – Ishnark