Example usage for org.hibernate.mapping ForeignKey getColumnIterator

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

Introduction

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

Prototype

public Iterator<Column> getColumnIterator() 

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   w w w.  j  a  v a 2  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> 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  av  a 2s. co 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.netspective.tool.hibernate.document.diagram.HibernateDiagramGenerator.java

License:Open Source License

public void generate() {
    final GraphvizDiagramGenerator gdg = getGraphvizDiagramGenerator();
    final HibernateDiagramGeneratorFilter filter = getDiagramFilter();
    final Set includedTables = new HashSet();

    for (final Iterator classes = configuration.getClassMappings(); classes.hasNext();) {
        final PersistentClass pclass = (PersistentClass) classes.next();
        final Table table = (Table) pclass.getTable();
        if (filter.includeClassInDiagram(this, pclass)) {
            final HibernateDiagramTableNodeGenerator nodeGenerator = filter.getTableNodeGenerator(this, pclass);
            final GraphvizDiagramNode node = nodeGenerator.generateTableNode(this, filter, pclass);
            filter.formatTableNode(this, pclass, node);
            gdg.addNode(node);/*from  w w  w.  ja  v a2  s  .  c  o  m*/
            includedTables.add(table);
        }
    }

    for (final Iterator classes = configuration.getClassMappings(); classes.hasNext();) {
        final PersistentClass pclass = (PersistentClass) classes.next();
        final Table table = (Table) pclass.getTable();
        if (includedTables.contains(table)) {
            FOREIGN_KEY: for (final Iterator fKeys = table.getForeignKeyIterator(); fKeys.hasNext();) {
                final ForeignKey foreignKey = (ForeignKey) fKeys.next();
                for (Iterator fKeyCols = foreignKey.getColumnIterator(); fKeyCols.hasNext();) {
                    final Column fKeyCol = (Column) fKeyCols.next();
                    if (!filter.includeColumnInDiagram(this, fKeyCol))
                        continue FOREIGN_KEY;
                }

                if (filter.includeForeignKeyEdgeInDiagram(this, foreignKey)
                        && includedTables.contains(foreignKey.getReferencedTable())) {
                    final HibernateDiagramTableNodeGenerator sourceTableNodeGenerator = filter
                            .getTableNodeGenerator(this, pclass);
                    final HibernateDiagramTableNodeGenerator refTableNodeGenerator = filter
                            .getTableNodeGenerator(this, getClassForTable(foreignKey.getReferencedTable()));

                    GraphvizDiagramEdge edge = new GraphvizDiagramEdge(gdg,
                            sourceTableNodeGenerator.getEdgeSourceElementAndPort(this, filter, foreignKey),
                            refTableNodeGenerator.getEdgeDestElementAndPort(this, filter, foreignKey));
                    filter.formatForeignKeyEdge(this, foreignKey, edge);
                    gdg.addEdge(edge);
                }
            }
        }
    }
}

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/*w w  w .  jav a  2  s. c om*/
 */
@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:org.teiid.spring.views.ViewBuilder.java

License:Apache License

@SuppressWarnings("unchecked")
private void addForeignKeys(org.hibernate.mapping.Table ormTable, Table view, MetadataFactory mf) {
    Collection<ForeignKey> fks = ormTable.getForeignKeys().values();
    for (ForeignKey fk : fks) {
        List<String> fkColumns = new ArrayList<>();
        List<String> refColumns = new ArrayList<>();
        Iterator<org.hibernate.mapping.Column> it = fk.getColumnIterator();
        while (it.hasNext()) {
            org.hibernate.mapping.Column c = it.next();
            fkColumns.add(c.getName());//w  w  w . jav a  2s.com
        }

        if (fk.isReferenceToPrimaryKey()) {
            List<org.hibernate.mapping.Column> columns = fk.getReferencedTable().getPrimaryKey().getColumns();
            for (org.hibernate.mapping.Column c : columns) {
                refColumns.add(c.getName());
            }

        } else {
            List<org.hibernate.mapping.Column> columns = fk.getReferencedColumns();
            for (org.hibernate.mapping.Column c : columns) {
                refColumns.add(c.getName());
            }
        }
        mf.addForeignKey(fk.getName(), fkColumns, refColumns, fk.getReferencedTable().getName(), view);
    }
}