阅读XML并创建多个表

时间:2017-01-23 01:13:07

标签: java sql xml jmx

我有一个XML输入文件,如下所示:

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

我创建了一个名为'Mbeans'的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中,我的应用程序可以根据需要使用此对象。这个输入文件告诉我需要从我拥有的特定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 个答案:

答案 0 :(得分: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*/);
}