Example usage for org.hibernate.mapping ForeignKey isPhysicalConstraint

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

Introduction

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

Prototype

public boolean isPhysicalConstraint() 

Source Link

Usage

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;/*from   www  .  ja  va  2s  . co 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;/*from   w  ww. ja va  2  s  .  com*/
    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:org.apereo.portal.tools.dbloader.HibernateDbLoader.java

License:Apache License

/** Generate the drop scripts and add them to the script list */
@SuppressWarnings("unchecked")
protected List<String> dropScript(Collection<Table> tables, Dialect dialect, String defaultCatalog,
        String defaultSchema) {//  ww  w .j  a v a  2s  .c  o  m
    final List<String> script = new ArrayList<String>(tables.size() * 2);

    if (dialect.dropConstraints()) {
        for (final Table table : tables) {
            if (table.isPhysicalTable()) {
                for (final Iterator<ForeignKey> subIter = table.getForeignKeyIterator(); subIter.hasNext();) {
                    final ForeignKey fk = subIter.next();
                    if (fk.isPhysicalConstraint()) {
                        script.add(fk.sqlDropString(dialect, defaultCatalog, defaultSchema));
                    }
                }
            }
        }
    }

    for (final Table table : tables) {
        if (table.isPhysicalTable()) {
            script.add(table.sqlDropString(dialect, defaultCatalog, defaultSchema));
        }
    }

    return script;
}

From source file:org.apereo.portal.tools.dbloader.HibernateDbLoader.java

License:Apache License

/** Generate create scripts and add them to the script list */
@SuppressWarnings("unchecked")
protected List<String> createScript(Collection<Table> tables, Dialect dialect, Mapping mapping,
        String defaultCatalog, String defaultSchema) {
    final List<String> script = new ArrayList<String>(tables.size() * 2);

    for (final Table table : tables) {
        if (table.isPhysicalTable()) {
            script.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
        }/*w  w w  .  j  a v  a  2  s.c  om*/
    }

    for (final Table table : tables) {
        if (table.isPhysicalTable()) {
            if (!dialect.supportsUniqueConstraintInCreateAlterTable()) {
                for (final Iterator<UniqueKey> subIter = table.getUniqueKeyIterator(); subIter.hasNext();) {
                    final UniqueKey uk = subIter.next();
                    final String constraintString = uk.sqlCreateString(dialect, mapping, defaultCatalog,
                            defaultSchema);
                    if (constraintString != null) {
                        script.add(constraintString);
                    }
                }
            }

            for (final Iterator<Index> subIter = table.getIndexIterator(); subIter.hasNext();) {
                final Index index = subIter.next();
                script.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
            }

            if (dialect.hasAlterTable()) {
                for (final Iterator<ForeignKey> subIter = table.getForeignKeyIterator(); subIter.hasNext();) {
                    final ForeignKey fk = subIter.next();
                    if (fk.isPhysicalConstraint()) {
                        script.add(fk.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
                    }
                }
            }
        }
    }

    return script;
}

From source file:org.beangle.orm.hibernate.tool.DdlGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
private void generateTableSql(Table table) {
    if (!table.isPhysicalTable())
        return;/*from  w ww. j  a v a2s  .  c om*/
    Iterator<String> commentIter = table.sqlCommentStrings(dialect, defaultCatalog, defaultSchema);
    while (commentIter.hasNext()) {
        comments.add(commentIter.next());
    }

    if (processed.contains(table))
        return;
    processed.add(table);
    tables.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));

    Iterator<UniqueKey> subIter = table.getUniqueKeyIterator();
    while (subIter.hasNext()) {
        UniqueKey uk = subIter.next();
        String constraintString = uk.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema);
        if (constraintString != null)
            constraints.add(constraintString);
    }

    Iterator<Index> idxIter = table.getIndexIterator();
    while (idxIter.hasNext()) {
        final Index index = idxIter.next();
        indexes.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
    }

    if (dialect.hasAlterTable()) {
        Iterator<ForeignKey> fkIter = table.getForeignKeyIterator();
        while (fkIter.hasNext()) {
            ForeignKey fk = fkIter.next();
            if (fk.isPhysicalConstraint()) {
                constraints.add(fk.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
            }
        }
    }
}

From source file:org.beangle.orm.hibernate.tool.DdlGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
private boolean isForeignColumn(Table table, Column column) {
    Iterator<ForeignKey> fkIter = table.getForeignKeyIterator();
    while (fkIter.hasNext()) {
        ForeignKey fk = fkIter.next();
        if (fk.isPhysicalConstraint()) {
            if (fk.getColumns().contains(column))
                return true;
        }/*from w  ww.  j  av a  2s.  c  om*/
    }
    return false;
}

From source file:org.jbpm.db.JbpmSchema.java

License:Open Source License

public String[] getCleanSql() {
    if (cleanSql == null) {
        // loop over all foreign key constraints
        List dropForeignKeysSql = new ArrayList();
        List createForeignKeysSql = new ArrayList();
        Iterator iter = configuration.getTableMappings();
        while (iter.hasNext()) {
            Table table = (Table) iter.next();
            if (table.isPhysicalTable()) {
                Iterator 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, properties.getProperty(Environment.DEFAULT_CATALOG),
                                        properties.getProperty(Environment.DEFAULT_SCHEMA)));
                        // and collect the create foreign key constraint sql
                        createForeignKeysSql.add(fk.sqlCreateString(dialect, mapping,
                                properties.getProperty(Environment.DEFAULT_CATALOG),
                                properties.getProperty(Environment.DEFAULT_SCHEMA)));
                    }// www . j av a 2  s  .co  m
                }
            }
        }

        List deleteSql = new ArrayList();
        iter = configuration.getTableMappings();
        while (iter.hasNext()) {
            Table table = (Table) iter.next();
            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 cleanSqlList = new ArrayList();
        cleanSqlList.addAll(dropForeignKeysSql);
        cleanSqlList.addAll(deleteSql);
        cleanSqlList.addAll(createForeignKeysSql);

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

From source file:org.jbpm.identity.hibernate.IdentitySchema.java

License:Open Source License

public String[] getCleanSql() {
    if (cleanSql == null) {
        // loop over all foreign key constraints
        List dropForeignKeysSql = new ArrayList();
        List createForeignKeysSql = new ArrayList();
        Iterator iter = configuration.getTableMappings();
        while (iter.hasNext()) {
            Table table = (Table) iter.next();
            if (table.isPhysicalTable()) {
                Iterator subIter = table.getForeignKeyIterator();
                while (subIter.hasNext()) {
                    ForeignKey fk = (ForeignKey) subIter.next();
                    if (fk.isPhysicalConstraint()) {
                        // collect the drop key constraint
                        dropForeignKeysSql.add(
                                fk.sqlDropString(dialect, properties.getProperty(Environment.DEFAULT_CATALOG),
                                        properties.getProperty(Environment.DEFAULT_SCHEMA)));
                        createForeignKeysSql.add(fk.sqlCreateString(dialect, mapping,
                                properties.getProperty(Environment.DEFAULT_CATALOG),
                                properties.getProperty(Environment.DEFAULT_SCHEMA)));
                    }/* ww  w  .ja  v  a  2s  .co  m*/
                }
            }
        }

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

        List cleanSqlList = new ArrayList();
        cleanSqlList.addAll(dropForeignKeysSql);
        cleanSqlList.addAll(deleteSql);
        cleanSqlList.addAll(createForeignKeysSql);

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

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.jav  a 2s. co 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();
    }
}

From source file:org.kuali.mobility.database.service.DatabaseServiceImpl.java

License:Open Source License

private String execute(String dialectStr, String delimiter, boolean overrideAlterTable) {
    PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();

    Map<String, Object> jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();
    jpaPropertyMap.put("hibernate.dialect", dialectStr);
    Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap)
            .getHibernateConfiguration();
    //       KMEDatabaseConfiguration c = (KMEDatabaseConfiguration) configuration;

    if (overrideAlterTable) {
        Iterator iter = configuration.getTableMappings();
        while (iter.hasNext()) {
            Table table = (Table) iter.next();
            if (table.isPhysicalTable()) {
                Iterator subIter = table.getForeignKeyIterator();
                while (subIter.hasNext()) {
                    ForeignKey fk = (ForeignKey) subIter.next();
                    if (fk.isPhysicalConstraint()) {
                        subIter.remove();
                    }/*w  w  w  .j  av a  2s .  co m*/
                }
            }
        }
    }

    Properties configurationProperties = configuration.getProperties();

    Dialect dialect = Dialect.getDialect(configurationProperties);
    //       if (dialect instanceof KMEDialect) {
    //          KMEDialect d = (KMEDialect) dialect;
    //          d.setOverrideAlterTable(overrideAlterTable);
    //       }

    Properties props = new Properties();
    props.putAll(dialect.getDefaultProperties());
    props.putAll(configurationProperties);

    String[] dropSQL = configuration.generateDropSchemaScript(dialect);
    String[] createSQL = configuration.generateSchemaCreationScript(dialect);

    Formatter formatter = (PropertiesHelper.getBoolean(Environment.FORMAT_SQL, props) ? FormatStyle.DDL
            : FormatStyle.NONE).getFormatter();
    boolean format = true;
    formatter = (format ? FormatStyle.DDL : FormatStyle.NONE).getFormatter();

    //      String delimiter = ";";
    StringBuffer output = new StringBuffer();
    for (String s : dropSQL) {
        output.append(formatMe(s, formatter, delimiter));
        output.append("\n");
    }
    for (String s : createSQL) {
        output.append(formatMe(s, formatter, delimiter));
        output.append("\n");
    }

    SchemaExport schema = new SchemaExport(configuration);
    //       schema.setFormat(true);
    //       schema.setDelimiter(";");
    //       schema.setOutputFile("/tmp/schema.sql");
    //     schema.create(false, false);

    //org.hibernate.dialect.Oracle10gDialect
    //org.hibernate.dialect.MySQL5Dialect
    return output.toString();
}