Example usage for org.hibernate.mapping Table getSchema

List of usage examples for org.hibernate.mapping Table getSchema

Introduction

In this page you can find the example usage for org.hibernate.mapping Table getSchema.

Prototype

public String getSchema() 

Source Link

Usage

From source file:com.blazebit.persistence.integration.hibernate.base.SimpleTableNameFormatter.java

License:Apache License

public String getQualifiedTableName(Dialect dialect, Table table) {
    final String catalogName = table.getCatalog();
    final String schemaName = table.getSchema();
    final String objectName = table.getName();

    StringBuilder buff = new StringBuilder();
    if (catalogName != null) {
        buff.append(catalogName.toString()).append('.');
    }//  w  w  w .  ja  v  a 2  s . c  o  m

    if (schemaName != null) {
        buff.append(schemaName.toString()).append('.');
    }

    buff.append(objectName.toString());
    return buff.toString();
}

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 .j  a 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;/*from   w ww.  j a va  2 s.  c  om*/
    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.clican.pluto.orm.tool.DatabaseMetadata.java

License:LGPL

public boolean isTable(Object key) throws HibernateException {
    if (key instanceof String) {
        Table tbl = new Table((String) key);
        if (getTableMetadata(tbl.getName(), tbl.getSchema(), tbl.getCatalog(), tbl.isQuoted()) != null) {
            return true;
        } else {/*from  w  w w .  j  a  va 2  s.  c o m*/
            String[] strings = StringHelper.split(".", (String) key);
            if (strings.length == 3) {
                tbl = new Table(strings[2]);
                tbl.setCatalog(strings[0]);
                tbl.setSchema(strings[1]);
                return getTableMetadata(tbl.getName(), tbl.getSchema(), tbl.getCatalog(),
                        tbl.isQuoted()) != null;
            } else if (strings.length == 2) {
                tbl = new Table(strings[1]);
                tbl.setSchema(strings[0]);
                return getTableMetadata(tbl.getName(), tbl.getSchema(), tbl.getCatalog(),
                        tbl.isQuoted()) != null;
            }
        }
    }
    return false;
}

From source file:com.github.shyiko.rook.target.hibernate4.cache.SynchronizationContext.java

License:Apache License

private Map<String, Integer> extractColumnMapping(Table table) throws SQLException {
    Map<String, Integer> result = new HashMap<String, Integer>();
    Connection connection = null;
    ConnectionProvider connectionProvider = getSessionFactory().getServiceRegistry()
            .getService(ConnectionProvider.class);
    try {/*w w  w .j a va  2 s  .  co  m*/
        connection = connectionProvider.getConnection();
        DatabaseMetaData meta = connection.getMetaData();
        ResultSet rs = meta.getColumns(table.getCatalog(), table.getSchema(), table.getName(), "%");
        try {
            int index = 0;
            while (rs.next()) {
                String column = rs.getString("COLUMN_NAME");
                if (column != null) {
                    result.put(column, index++);
                }
            }
        } finally {
            rs.close();
        }
    } finally {
        connectionProvider.closeConnection(connection);
    }
    return result;
}

From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java

License:Open Source License

private void manageIdentityGenerator(Mappings mappings, Table tab, SimpleValue id) {
    id.setIdentifierGeneratorStrategy("identity");
    Properties params = new Properties();
    params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer());

    params.setProperty(PersistentIdentifierGenerator.SCHEMA, escapeName(tab.getSchema()));
    id.setIdentifierGeneratorProperties(params);
    id.setNullValue(null);/*from   ww  w  .  j a  v  a 2s  .  c o m*/
}

From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java

License:Open Source License

private void manageSequenceGenerator(Mappings mappings, Table tab, SimpleValue id,
        SequenceGenerator generator) {/*ww  w . ja va  2  s .  c om*/
    id.setIdentifierGeneratorStrategy("enhanced-sequence");
    Properties params = new Properties();
    params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer());
    params.put(SequenceStyleGenerator.SEQUENCE_PARAM, escapeName(generator.getName()));
    params.setProperty(SequenceStyleGenerator.SCHEMA, escapeName(tab.getSchema()));
    id.setIdentifierGeneratorProperties(params);
    id.setNullValue(null);
}

From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java

License:Open Source License

private void manageTableGenerator(Mappings mappings, Table tab, SimpleValue id,
        com.manydesigns.portofino.model.database.TableGenerator generator) {
    id.setIdentifierGeneratorStrategy("enhanced-table");
    Properties params = new Properties();
    params.put(TableGenerator.TABLE, tab);
    params.put(TableGenerator.TABLE_PARAM, escapeName(generator.getTable()));
    params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer());
    params.put(TableGenerator.SEGMENT_COLUMN_PARAM, escapeName(generator.getKeyColumn()));
    params.put(TableGenerator.SEGMENT_VALUE_PARAM, generator.getKeyValue());
    params.put(TableGenerator.VALUE_COLUMN_PARAM, escapeName(generator.getValueColumn()));
    params.setProperty(TableGenerator.SCHEMA, escapeName(tab.getSchema()));
    id.setIdentifierGeneratorProperties(params);
    id.setNullValue(null);/*from   ww w . j a v a2 s  .  c  o  m*/
}

From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java

License:Open Source License

private void manageIncrementGenerator(Mappings mappings, Table tab, SimpleValue id, String entityName) {
    id.setIdentifierGeneratorStrategy("increment");
    Properties params = new Properties();
    params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer());
    params.setProperty(PersistentIdentifierGenerator.SCHEMA, escapeName(tab.getSchema()));
    params.put(IncrementGenerator.ENTITY_NAME, entityName);
    id.setIdentifierGeneratorProperties(params);
    id.setNullValue(null);//w  ww.j  a va 2s. c  o  m
}

From source file:com.siemens.scr.avt.ad.query.common.DicomMappingDictionaryLoadingStrategy.java

License:Open Source License

private void loadPersistentClass(DicomMappingDictionary dict, PersistentClass pc) {
    Table table = pc.getTable();
    Iterator<Property> it = pc.getPropertyIterator();
    while (it.hasNext()) {
        Property prop = it.next();//  w  w  w  .  ja v a 2  s. c om
        loadProperty(dict, prop, table, pc.getClassName());
    }
    String tableName = table.getSchema() + "." + table.getName();
    String key = pc.getClassName();
    dict.put(key, new WildcardEntry(tableName));
}