Example usage for org.hibernate.mapping ForeignKey getName

List of usage examples for org.hibernate.mapping ForeignKey getName

Introduction

In this page you can find the example usage for org.hibernate.mapping ForeignKey getName.

Prototype

public String getName() 

Source Link

Usage

From source file:alma.acs.tmcdb.translator.AbstractReverseEngineeringStrategy.java

License:Open Source License

@Override
public AssociationInfo foreignKeyToAssociationInfo(ForeignKey foreignKey) {
    DefaulAssociationInfo info = new DefaulAssociationInfo();

    String name = foreignKey.getName();
    for (int i = 0; i < inheritanceTranslators.length; i++) {
        CascadeType cType = inheritanceTranslators[i].getCascadeTypeForForeigKey(name);
        if (cType != null) {
            if (cType == CascadeType.NONE) {
                info.setCascade("none"); // if not set, it produces an EJB3 "all" cascading
                break;
            } else if (cType == CascadeType.AGGREGATION) {
                info.setCascade("save-update, persist, lock");
                break;
            } else if (cType == CascadeType.COMPOSITION) {
                info.setCascade("all-delete-orphan");
                break;
            } else {
                info.setCascade("none"); // fallback
                break;
            }/* w  w w . j  a  v a  2 s. c o  m*/
        }
    }

    return info;
}

From source file:alma.acs.tmcdb.translator.AbstractReverseEngineeringStrategy.java

License:Open Source License

@Override
public AssociationInfo foreignKeyToInverseAssociationInfo(ForeignKey foreignKey) {
    DefaulAssociationInfo info = new DefaulAssociationInfo();

    String name = foreignKey.getName();
    for (int i = 0; i < inheritanceTranslators.length; i++) {
        CascadeType cType = inheritanceTranslators[i].getCascadeTypeForForeigKey(name);
        if (cType != null) {
            if (cType == CascadeType.AGGREGATION_INVERSE) {
                info.setCascade("save-update, persist, lock");
                break;
            } else if (cType == CascadeType.COMPOSITION_INVERSE) {
                info.setCascade("all-delete-orphan");
                break;
            } else {
                info.setCascade("none"); // fallback
                break;
            }//from   ww  w  . j a v a2  s .co m
        }
    }

    return info;
}

From source file:com.clican.pluto.orm.dynamic.impl.DataBaseOperationImpl.java

License:LGPL

@SuppressWarnings("unchecked")
public void alterTable(Configuration cfg, ModelDescription oldOne, ModelDescription newOne) {
    Connection conn = null;/* ww  w  .  ja  v a  2s  . c  o m*/
    DatabaseMetadata meta = null;
    String defaultCatalog = cfg.getProperties().getProperty(Environment.DEFAULT_CATALOG);
    String defaultSchema = cfg.getProperties().getProperty(Environment.DEFAULT_SCHEMA);
    List<String> alterSqls = new ArrayList<String>();
    try {
        conn = dataSource.getConnection();
        meta = new DatabaseMetadata(conn, dialect);
        Mapping mapping = cfg.buildMapping();
        // Alter table name;
        if (!oldOne.getName().equals(newOne.getName())) {
            String alterTableName = "alter table " + dialect.openQuote() + oldOne.getName().toUpperCase()
                    + dialect.closeQuote() + "rename to " + dialect.openQuote() + newOne.getName().toUpperCase()
                    + dialect.closeQuote();
            executeSql(conn, alterTableName);
        }

        List<PropertyDescription> oldPropertyDescriptionList = oldOne.getPropertyDescriptionList();
        List<PropertyDescription> currentPropertyDescriptionList = newOne.getPropertyDescriptionList();
        List<PropertyDescription> removePropertyList = new ArrayList<PropertyDescription>();
        List<PropertyDescription> addPropertyList = new ArrayList<PropertyDescription>(
                currentPropertyDescriptionList);
        Map<PropertyDescription, PropertyDescription> pdMap = new HashMap<PropertyDescription, PropertyDescription>();
        for (PropertyDescription pd1 : oldPropertyDescriptionList) {
            boolean remove = true;
            for (PropertyDescription pd2 : currentPropertyDescriptionList) {
                if (pd1.getId().equals(pd2.getId())) {
                    addPropertyList.remove(pd2);
                    if (!pd1.equals(pd2)) {
                        pdMap.put(pd2, pd1);
                    }
                    remove = false;
                    break;
                }
            }
            if (remove) {
                removePropertyList.add(pd1);
            }
        }

        Iterator<Table> tableIter = cfg.getTableMappings();
        while (tableIter.hasNext()) {
            Table table = tableIter.next();
            TableMetadata tableInfo = meta.getTableMetadata(table.getName(),
                    (table.getSchema() == null) ? defaultSchema : table.getSchema(),
                    (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted()

            );
            if (tableInfo == null) {
                alterSqls.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
            } else {
                if (!table.getName().equalsIgnoreCase(newOne.getName())) {
                    continue;
                }
                for (PropertyDescription removeProperty : removePropertyList) {
                    if (removeProperty.getControl().isSupportMutil()
                            && removeProperty.getControl().isDynamic()) {
                        alterSqls.add("drop table " + dialect.openQuote() + newOne.getName().toUpperCase() + "_"
                                + removeProperty.getName().toUpperCase() + "_RELATION" + dialect.closeQuote());
                    } else {
                        if (((DialectExtention) dialect).needDropForeignKeyBeforeDropColumn()) {
                            ForeignKeyMetadata fkm = tableInfo.getForeignKeyMetadataByColumnNames(
                                    new String[] { removeProperty.getName().toUpperCase() });
                            if (fkm != null) {
                                alterSqls.add("alter table " + dialect.openQuote()
                                        + newOne.getName().toUpperCase() + dialect.closeQuote() + " "
                                        + dialect.getDropForeignKeyString() + " " + dialect.openQuote()
                                        + fkm.getName() + dialect.closeQuote());
                            }
                        }
                        alterSqls.add("alter table " + dialect.openQuote() + newOne.getName().toUpperCase()
                                + dialect.closeQuote() + " drop column " + dialect.openQuote()
                                + removeProperty.getName().toUpperCase() + dialect.closeQuote());
                    }
                }
                StringBuffer root = new StringBuffer("alter table ")
                        .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' ')
                        .append(dialect.getAddColumnString());
                Iterator<Column> iter = table.getColumnIterator();
                while (iter.hasNext()) {
                    Column column = iter.next();
                    PropertyDescription pd = null;
                    if ((pd = contains(column.getName(), addPropertyList)) != null) {
                        StringBuffer alter = new StringBuffer(root.toString()).append(' ')
                                .append(column.getQuotedName(dialect)).append(' ')
                                .append(column.getSqlType(dialect, mapping));

                        String defaultValue = column.getDefaultValue();
                        if (defaultValue != null) {
                            alter.append(" default ").append(defaultValue);

                            if (column.isNullable()) {
                                alter.append(dialect.getNullColumnString());
                            } else {
                                alter.append(" not null");
                            }

                        }

                        boolean useUniqueConstraint = column.isUnique() && dialect.supportsUnique()
                                && (!column.isNullable() || dialect.supportsNotNullUnique());
                        if (useUniqueConstraint) {
                            alter.append(" unique");
                        }

                        if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) {
                            alter.append(" check(").append(column.getCheckConstraint()).append(")");
                        }

                        String columnComment = column.getComment();
                        if (columnComment != null) {
                            alter.append(dialect.getColumnComment(columnComment));
                        }

                        alterSqls.add(alter.toString());
                    } else if ((pd = contains(column.getName(), pdMap)) != null) {
                        PropertyDescription newPd = pd;
                        PropertyDescription oldPd = pdMap.get(pd);
                        if (!oldPd.getName().equalsIgnoreCase(newPd.getName())) {
                            StringBuffer renameColumn = new StringBuffer("alter table ")
                                    .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                                    .append(' ').append(((DialectExtention) dialect).getRenameColumnString(
                                            oldPd.getName().toUpperCase(), newPd.getName().toUpperCase()));
                            if (((DialectExtention) dialect).isAddColumnDefinitionWhenRename()) {
                                renameColumn.append(" ");
                                renameColumn.append(column.getSqlType(dialect, mapping));
                            }
                            executeSql(conn, renameColumn.toString());
                        }

                        StringBuffer alterColumn = new StringBuffer("alter table ")
                                .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                                .append(' ').append(((DialectExtention) dialect).getModifyColumnString(column))
                                .append(' ').append(column.getQuotedName(dialect));
                        alterColumn.append(" ");
                        alterColumn.append(column.getSqlType(dialect, mapping));
                        String defaultValue = column.getDefaultValue();
                        if (defaultValue != null) {
                            alterColumn.append(" default ").append(defaultValue);

                            if (column.isNullable()) {
                                alterColumn.append(dialect.getNullColumnString());
                            } else {
                                alterColumn.append(" not null");
                            }

                        }

                        boolean useUniqueConstraint = column.isUnique() && dialect.supportsUnique()
                                && (!column.isNullable() || dialect.supportsNotNullUnique());
                        if (useUniqueConstraint) {
                            alterColumn.append(" unique");
                        }

                        if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) {
                            alterColumn.append(" check(").append(column.getCheckConstraint()).append(")");
                        }

                        String columnComment = column.getComment();
                        if (columnComment != null) {
                            alterColumn.append(dialect.getColumnComment(columnComment));
                        }
                        alterSqls.add(alterColumn.toString());
                    }
                }
            }
        }
        tableIter = cfg.getTableMappings();
        while (tableIter.hasNext()) {
            Table table = tableIter.next();
            Iterator<ForeignKey> subIter = table.getForeignKeyIterator();
            while (subIter.hasNext()) {
                ForeignKey fk = (ForeignKey) subIter.next();
                if (fk.isPhysicalConstraint()) {
                    TableMetadata tableInfo = meta.getTableMetadata(table.getName(),
                            (table.getSchema() == null) ? defaultSchema : table.getSchema(),
                            (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted()

                    );
                    if (tableInfo == null) {
                        String[] cols = new String[fk.getColumnSpan()];
                        String[] refcols = new String[fk.getColumnSpan()];
                        int i = 0;
                        Iterator<Column> refiter = null;
                        if (fk.isReferenceToPrimaryKey()) {
                            refiter = fk.getReferencedTable().getPrimaryKey().getColumnIterator();
                        } else {
                            refiter = fk.getReferencedColumns().iterator();
                        }

                        Iterator<Column> columnIter = fk.getColumnIterator();
                        while (columnIter.hasNext()) {
                            cols[i] = ((Column) columnIter.next()).getQuotedName(dialect);
                            refcols[i] = ((Column) refiter.next()).getQuotedName(dialect);
                            i++;
                        }
                        String result = dialect
                                .getAddForeignKeyConstraintString(
                                        fk.getName(), cols, fk.getReferencedTable().getQualifiedName(dialect,
                                                defaultCatalog, defaultSchema),
                                        refcols, fk.isReferenceToPrimaryKey());
                        StringBuffer createFK = new StringBuffer("alter table ")
                                .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                                .append(dialect.supportsCascadeDelete() ? result + " on delete cascade"
                                        : result);
                        alterSqls.add(createFK.toString());
                    }
                }
            }
        }
        this.executeSqls(conn, alterSqls);
    } catch (Exception e) {
        throw new PlutoException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }
}

From source file:com.clican.pluto.orm.dynamic.impl.DataBaseOperationImpl.java

License:LGPL

@SuppressWarnings("unchecked")
public void createTable(Configuration cfg) {
    Connection conn = null;//  ww  w .  j  a  va2  s  .  c o  m
    DatabaseMetadata meta = null;
    String defaultCatalog = cfg.getProperties().getProperty(Environment.DEFAULT_CATALOG);
    String defaultSchema = cfg.getProperties().getProperty(Environment.DEFAULT_SCHEMA);
    List<String> createSqls = new ArrayList<String>();
    try {
        conn = dataSource.getConnection();
        meta = new DatabaseMetadata(conn, dialect);
        Iterator<Table> tableIter = cfg.getTableMappings();
        Mapping mapping = cfg.buildMapping();
        while (tableIter.hasNext()) {
            Table table = (Table) tableIter.next();
            TableMetadata tableInfo = meta.getTableMetadata(table.getName(),
                    (table.getSchema() == null) ? defaultSchema : table.getSchema(),
                    (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted()

            );
            if (tableInfo == null) {
                createSqls.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
            }
        }
        tableIter = cfg.getTableMappings();
        while (tableIter.hasNext()) {
            Table table = (Table) tableIter.next();
            Iterator<ForeignKey> subIter = table.getForeignKeyIterator();
            while (subIter.hasNext()) {
                ForeignKey fk = (ForeignKey) subIter.next();
                if (fk.isPhysicalConstraint()) {
                    TableMetadata tableInfo = meta.getTableMetadata(table.getName(),
                            (table.getSchema() == null) ? defaultSchema : table.getSchema(),
                            (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted()

                    );
                    if (tableInfo == null) {
                        String[] cols = new String[fk.getColumnSpan()];
                        String[] refcols = new String[fk.getColumnSpan()];
                        int i = 0;
                        Iterator<Column> refiter = null;
                        if (fk.isReferenceToPrimaryKey()) {
                            refiter = fk.getReferencedTable().getPrimaryKey().getColumnIterator();
                        } else {
                            refiter = fk.getReferencedColumns().iterator();
                        }

                        Iterator<Column> columnIter = fk.getColumnIterator();
                        while (columnIter.hasNext()) {
                            cols[i] = ((Column) columnIter.next()).getQuotedName(dialect);
                            refcols[i] = ((Column) refiter.next()).getQuotedName(dialect);
                            i++;
                        }
                        String result = dialect
                                .getAddForeignKeyConstraintString(
                                        fk.getName(), cols, fk.getReferencedTable().getQualifiedName(dialect,
                                                defaultCatalog, defaultSchema),
                                        refcols, fk.isReferenceToPrimaryKey());
                        StringBuffer createFK = new StringBuffer("alter table ")
                                .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                                .append(dialect.supportsCascadeDelete() ? result + " on delete cascade"
                                        : result);
                        createSqls.add(createFK.toString());
                    }
                }
            }
        }
        this.executeSqls(conn, createSqls);
    } catch (DDLException e) {
        throw e;
    } catch (Exception e) {
        throw new PlutoException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

}

From source file:com.xpn.xwiki.store.migration.hibernate.R40000XWIKI6990DataMigration.java

License:Open Source License

/**
 * Append commands to drop all foreign keys of a given table.
 *
 * @param sb the string builder to append to
 * @param table the table to process/*www .j  a v a 2 s  .  c o  m*/
 */
@SuppressWarnings("unchecked")
private void appendDropForeignKeyChangeLog(StringBuilder sb, Table table) {
    Iterator<ForeignKey> fki = table.getForeignKeyIterator();

    // Preamble
    String tableName = table.getName();
    sb.append("  <changeSet id=\"R").append(this.getVersion().getVersion()).append('-')
            .append(Util.getHash(String.format("dropForeignKeyConstraint-%s", tableName)))
            .append("\" author=\"xwiki\" runOnChange=\"true\" runAlways=\"true\" failOnError=\"false\">\n")
            .append("    <comment>Drop foreign keys on table [").append(tableName).append("]</comment>\n");

    // Concrete Property types should each have a foreign key referencing the BaseProperty
    // Other classes don't have any foreign keys at all, in which case the fast exit path above was used
    while (fki.hasNext()) {
        ForeignKey fk = fki.next();
        // Drop the old constraint
        if (fk.isReferenceToPrimaryKey()) {
            sb.append("    <dropForeignKeyConstraint baseTableName=\"").append(tableName)
                    .append("\" constraintName=\"").append(fk.getName()).append("\" />\n");
        }
    }
    // All done!
    sb.append("  </changeSet>\n");
    this.logCount++;
}

From source file:com.xpn.xwiki.store.migration.hibernate.R40000XWIKI6990DataMigration.java

License:Open Source License

/**
 * Append change log to add foreign keys with CASCADEd updates.
 *
 * @param sb the string builder to append to the add tasks
 * @param table the table to process/*from w w  w .j ava  2s .  c  o m*/
 */
@SuppressWarnings("unchecked")
private void appendAddForeignKeyChangeLog(StringBuilder sb, Table table) {
    Iterator<ForeignKey> fki = table.getForeignKeyIterator();

    // Preamble
    String tableName = table.getName();
    sb.append("  <changeSet id=\"R").append(this.getVersion().getVersion()).append('-')
            .append(Util.getHash(String.format("addForeignKeyConstraint-%s", tableName)))
            .append("\" author=\"xwiki\" runOnChange=\"true\" runAlways=\"true\">\n")
            .append("    <comment>Add foreign keys on table [").append(tableName)
            .append("] to use ON UPDATE CASCADE</comment>\n");

    // Concrete Property types should each have a foreign key referencing the BaseProperty
    // Other classes don't have any foreign keys at all, in which case the fast exit path above was used
    while (fki.hasNext()) {
        ForeignKey fk = fki.next();

        if (fk.isReferenceToPrimaryKey()) {
            // Recreate the constraint
            sb.append("    <addForeignKeyConstraint constraintName=\"").append(fk.getName())
                    .append("\" baseTableName=\"").append(tableName).append("\"  baseColumnNames=\"");

            // Reuse the data from the old foreign key
            // Columns in the current table
            Iterator<Column> columns = fk.getColumnIterator();
            while (columns.hasNext()) {
                Column column = columns.next();
                sb.append(column.getName());
                if (columns.hasNext()) {
                    sb.append(",");
                }
            }
            sb.append("\" referencedTableName=\"").append(fk.getReferencedTable().getName())
                    .append("\" referencedColumnNames=\"");

            // Columns in the referenced table
            columns = fk.getReferencedTable().getPrimaryKey().getColumnIterator();
            while (columns.hasNext()) {
                Column column = columns.next();
                sb.append(column.getName());
                if (columns.hasNext()) {
                    sb.append(",");
                }
            }

            // The important part: cascaded updates
            if (this.isOracle) {
                // Oracle doesn't support cascaded updates, but allow the constraint to be checked
                // at the commit level (normal checking is done at the statement level).
                sb.append("\" initiallyDeferred=\"true\"/>\n");
            } else {
                sb.append("\" onUpdate=\"CASCADE\"/>\n");
            }
        }
    }
    // All done!
    sb.append("  </changeSet>\n");
    this.logCount++;
}

From source file:com.zutubi.pulse.master.hibernate.SchemaRefactor.java

License:Apache License

private void transferForeignKeys(Connection connection, Table fromTable, Table toTable) throws SQLException {
    DatabaseMetadata meta = new DatabaseMetadata(connection, dialect);

    Iterator i = config.getTableMappings();
    while (i.hasNext()) {
        Table t = (Table) i.next();//from w w w. j a v a 2s  .co  m
        Iterator fki = t.getForeignKeyIterator();
        while (fki.hasNext()) {
            ForeignKey fk = (ForeignKey) fki.next();
            Table referencedTable = fk.getReferencedTable();
            if (referencedTable != null && referencedTable == fromTable) {
                TableMetadata tableInfo = meta.getTableMetadata(t.getName(), defaultSchema, defaultCatalog,
                        false);

                // verify that the fk is actually in the database.
                if (tableInfo.getForeignKeyMetadata(fk.getName()) == null) {
                    // foreign key does not exist, so do not drop or recreate it.
                    continue;
                }

                String sql = fk.sqlDropString(dialect, defaultCatalog, defaultSchema);
                LOG.info(sql);
                JDBCUtils.execute(connection, sql);
                fk.setReferencedTable(toTable);

                sql = fk.sqlCreateString(dialect, null, defaultCatalog, defaultSchema);
                LOG.info(sql);
                JDBCUtils.execute(connection, sql);
            }
        }
    }
}

From source file:com.zutubi.pulse.master.hibernate.SchemaRefactor.java

License:Apache License

protected Table clone(Table table) {
    Table clone = new Table(table.getName());
    clone.setAbstract(table.isAbstract());
    clone.setCatalog(table.getCatalog());
    clone.setComment(table.getComment());
    clone.setName(table.getName());//from w w w. j av a  2  s .c om
    clone.setPrimaryKey(table.getPrimaryKey());
    clone.setQuoted(table.isQuoted());
    clone.setRowId(table.getRowId());
    clone.setSchema(table.getSchema());
    clone.setSubselect(table.getSubselect());

    Iterator columns = table.getColumnIterator();
    while (columns.hasNext()) {
        Column column = (Column) columns.next();
        clone.addColumn(column);
    }

    Iterator foreignKeys = table.getForeignKeyIterator();
    while (foreignKeys.hasNext()) {
        ForeignKey key = (ForeignKey) foreignKeys.next();
        clone.createForeignKey(key.getName(), key.getColumns(), key.getReferencedEntityName(),
                key.getReferencedColumns());
    }

    return clone;
}

From source file:net.lshift.hibernate.migrations.AlterTableBuilder.java

License:Apache License

public AlterTableBuilder addForeignKey(String name, String[] columnNames, String referencedTable,
        String[] referencedColumns) {
    ForeignKey fk = new ForeignKey();
    fk.setName(name);//from   w ww  . j a  v  a 2  s. co  m
    for (String col : columnNames)
        fk.addColumn(new Column(col));
    fk.setTable(new Table(table));

    PrimaryKey refPrimaryKey = new PrimaryKey();
    for (String col : referencedColumns)
        refPrimaryKey.addColumn(new Column(col));
    Table refTable = new Table(referencedTable);
    refTable.setPrimaryKey(refPrimaryKey);

    fk.setReferencedTable(refTable);

    String defaultCatalog = config.getProperties().getProperty(Environment.DEFAULT_CATALOG);
    String defaultSchema = config.getProperties().getProperty(Environment.DEFAULT_SCHEMA);

    // fk.sqlConstraintString appears to generate incorrect SQL against MySQL in some instances.
    // The referenced columns are not always correctly listed.
    //    alterFragments.add(" add index " + fk.getName() + " (" + StringHelper.join(", ", columnNames) +
    //        "), add constraint " + fk.getName() + " foreign key (" + StringHelper.join(", ", columnNames) +
    //        " references " + referencedTable + " (" + StringHelper.join(", ", referencedColumns) + ")");
    alterFragments.add(fk.sqlConstraintString(dialect, fk.getName(), defaultCatalog, defaultSchema));
    return this;
}

From source file:org.jbpm.test.Db.java

License:Open Source License

public static void clean(ProcessEngine processEngine) {
    SessionFactory sessionFactory = processEngine.get(SessionFactory.class);
    // when running this with a remote ejb invocation configuration, there is no
    // session factory and no cleanup needs to be done
    if (sessionFactory == null) {
        return;/*from  ww w  .  j a v  a 2 s  . c  o  m*/
    }

    String[] cleanSql = cleanSqlCache.get(processEngine);

    if (cleanSql == null) {
        Configuration configuration = processEngine.get(Configuration.class);

        SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory;
        Dialect dialect = sessionFactoryImplementor.getDialect();

        // loop over all foreign key constraints
        List<String> dropForeignKeysSql = new ArrayList<String>();
        List<String> createForeignKeysSql = new ArrayList<String>();
        Iterator<Table> iter = configuration.getTableMappings();

        //if no session-factory is build, the configuration is not fully initialized.
        //Hence, the ForeignKey's won't have a referenced table. This is calculated on 
        //second pass.
        configuration.buildMappings();

        while (iter.hasNext()) {
            Table table = (Table) iter.next();
            if (table.isPhysicalTable()) {
                String catalog = table.getCatalog();
                String schema = table.getSchema();
                Iterator<ForeignKey> subIter = table.getForeignKeyIterator();
                while (subIter.hasNext()) {
                    ForeignKey fk = (ForeignKey) subIter.next();
                    if (fk.isPhysicalConstraint()) {
                        // collect the drop foreign key constraint sql
                        dropForeignKeysSql.add(fk.sqlDropString(dialect, catalog, schema));
                        // MySQLDialect creates an index for each foreign key.
                        // see
                        // http://opensource.atlassian.com/projects/hibernate/browse/HHH-2155
                        // This index should be dropped or an error will be thrown during
                        // the creation phase
                        if (dialect instanceof MySQLDialect) {
                            dropForeignKeysSql
                                    .add("alter table " + table.getName() + " drop key " + fk.getName());
                        }
                        // and collect the create foreign key constraint sql
                        createForeignKeysSql
                                .add(fk.sqlCreateString(dialect, sessionFactoryImplementor, catalog, schema));
                    }
                }
            }
        }

        List<String> deleteSql = new ArrayList<String>();
        iter = configuration.getTableMappings();
        while (iter.hasNext()) {
            Table table = (Table) iter.next();
            if (table.isPhysicalTable()) {
                deleteSql.add("delete from " + table.getName());
            }
        }

        // glue
        // - drop foreign key constraints
        // - delete contents of all tables
        // - create foreign key constraints
        // together to form the clean script
        List<String> cleanSqlList = new ArrayList<String>();
        cleanSqlList.addAll(dropForeignKeysSql);
        cleanSqlList.addAll(deleteSql);
        cleanSqlList.addAll(createForeignKeysSql);

        cleanSql = (String[]) cleanSqlList.toArray(new String[cleanSqlList.size()]);

        cleanSqlCache.put(processEngine, cleanSql);
    }

    Session session = sessionFactory.openSession();
    try {
        for (String query : cleanSql) {
            // log.trace(query);
            session.createSQLQuery(query).executeUpdate();
        }
    } finally {
        session.close();
    }
}