如何在hibernate中动态创建映射文件?

时间:2011-09-28 04:47:20

标签: hibernate

我有动态创建表的情况,我不知道它动态出现的表名,所以我想知道我怎样才能动态创建映射文件(.cfg.xml),有可能或者不?

由于

1 个答案:

答案 0 :(得分:2)

是的,这是可能的。

我这样做:

    String xml = generate(data, dialect);

    Configuration configuration = new Configuration();
    configuration.addXML(xml);


public static String generate(Data pData, Dialect pDialect) {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version='1.0' encoding='UTF-8'?>");
    sb.append("<!DOCTYPE hibernate-mapping PUBLIC '-//Hibernate/Hibernate Mapping DTD//EN' "
                    + "'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>");
    sb.append("<hibernate-mapping>");
    sb.append(String.format("<class name='dummy' table='%s'>", pData.getTable()));

    final IMyColumn primaryKeyColumn = pData.getPrimaryKey().get(0);
    sb.append(addItem(pData, primaryKeyColumn, "id", pDialect));

    for (IMyColumn column : pData.getColumns()) {
        if (!column.equals(primaryKeyColumn)) {
            sb.append(addItem(column, PROPERTY, pDialect));
        }
    }
    sb.append("</class>");
    sb.append("</hibernate-mapping>");
    final String xml = sb.toString();
    //System.out.println(xml);
    return xml;
}