Example usage for org.hibernate.mapping Table getName

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

Introduction

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

Prototype

public String getName() 

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('.');
    }/*from w  w  w.ja  va  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.common.support.spring.AnnotationSessionFactoryBean.java

License:LGPL

@SuppressWarnings("unchecked")
@Override//from w w w.j  av a 2  s  .c  o m
protected void postProcessAnnotationConfiguration(AnnotationConfiguration config) throws HibernateException {
    if (customizedSchema == null) {
        return;
    }
    Map<String, String> schemaMapping = new HashMap<String, String>();
    Iterator<Table> it = (Iterator<Table>) config.getTableMappings();
    while (it.hasNext()) {
        Table table = it.next();
        String name = table.getName();
        if (customizedSchema.containsKey(name.toUpperCase())) {
            table.setSchema(customizedSchema.get(name.toUpperCase()));
            schemaMapping.put(name.toUpperCase(), customizedSchema.get(name.toUpperCase()));
        } else {
            if (StringUtils.isNotEmpty(defaultSchema)) {
                table.setSchema(defaultSchema);
                schemaMapping.put(name.toUpperCase(), defaultSchema);
            }
        }
    }
}

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  a2  s.  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;//  w ww  .j  av a2 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.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  ww  w .  j  a  va 2s  .  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.clueride.rest.MemberWebService.java

License:Apache License

private void dumpEntities() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();

    for (PersistentClass persistentClass : metadata.getEntityBindings()) {

        Table table = persistentClass.getTable();

        LOGGER.info(String.format("Entity: {} is mapped to table: {}", persistentClass.getClassName(),
                table.getName()));

        for (Iterator propertyIterator = persistentClass.getPropertyIterator(); propertyIterator.hasNext();) {
            Property property = (Property) propertyIterator.next();

            for (Iterator columnIterator = property.getColumnIterator(); columnIterator.hasNext();) {
                Column column = (Column) columnIterator.next();

                LOGGER.info(String.format("Property: {} is mapped on table column: {} of type: {}",
                        property.getName(), column.getName(), column.getSqlType()));
            }/*from ww  w  .j a v  a2  s.  c  o  m*/
        }
    }
}

From source file:com.evolveum.midpoint.repo.sql.schemacheck.SchemaChecker.java

License:Apache License

private boolean areSomeTablesPresent(Metadata metadata) {
    Collection<String> presentTables = new ArrayList<>();
    Collection<String> missingTables = new ArrayList<>();
    for (Table table : metadata.collectTableMappings()) {
        String tableName = table.getName();
        try (Session session = baseHelper.beginReadOnlyTransaction()) {
            List<?> result = session.createNativeQuery("select count(*) from " + tableName).list();
            LOGGER.debug("Table {} seems to be present; number of records is {}", tableName, result);
            presentTables.add(tableName);
        } catch (Throwable t) {
            LOGGER.debug("Table {} seems to be missing: {}", tableName, t.getMessage(), t);
            missingTables.add(tableName);
        }/*from w w w  . j  a  v a2 s .  co  m*/
    }
    LOGGER.info("The following midPoint tables are present (not necessarily well-defined): {}", presentTables);
    LOGGER.info("Couldn't find the following midPoint tables: {}", missingTables);
    return !presentTables.isEmpty();
}

From source file:com.fiveamsolutions.nci.commons.audit.AuditLogInterceptor.java

License:Open Source License

/**
 * Retrieves the table name and the column name for the given class and property.
 *
 * @param className//w w  w. ja v a  2  s.  c  om
 * @param fieldName
 * @return Map
 */
private synchronized Map<String, String> getColumnTableName(String className, String fieldName) {
    String hashkey = className + ";" + fieldName;
    Map<String, String> retMap = COLUMN_CACHE.get(hashkey);
    if (retMap != null) {
        return retMap;
    }

    retMap = new HashMap<String, String>();
    COLUMN_CACHE.put(hashkey, retMap);

    PersistentClass pc = getHibernateHelper().getConfiguration().getClassMapping(className);
    // get the table and column information
    Table table = pc.getTable();
    String tableName = table.getName();
    String columnName = getColumnName(pc, fieldName);
    if (columnName == null) {
        columnName = fieldName;
    }
    retMap.put(TABLE_NAME, tableName);
    retMap.put(COLUMN_NAME, columnName);
    return retMap;
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

License:Apache License

public String updateCreateConstraint(Dialect dialect, StringBuffer buf, String name, Table table,
        Constraint constraint) {// w ww . j  a v  a2  s  .c  om
    NamingStrategy namingStrategy = getProfile().getNamingStrategy();
    String newName = namingStrategy.constraintName(constraint,
            getEntityClassName(namingStrategy.tableName(table.getName())));

    if (!name.equals(newName)) {
        String sqlCreate = buf.toString();
        Matcher matcher = CONSTRAINT_PATTERN.matcher(sqlCreate);
        if (matcher.find()) {
            buf = new StringBuffer();
            buf.append(sqlCreate.substring(0, matcher.start(1)));
            buf.append(newName);
            buf.append(sqlCreate.substring(matcher.end(1)));
        }
        name = newName;
    }

    String tableNameLC = getProfile().getNamingStrategy().tableName(table.getName()).toLowerCase();

    if (!renderTable(tableNameLC) || externalViews.contains(tableNameLC)) {
        return "-- skipped creation of constraint '" + name + "' for table '" + table.getName()
                + "' as the mapped entity was not chosen to be processed or is a view";
    }

    TableConfig tableConfig = tblNameToConfig.get(tableNameLC);

    String refTblNameLC = null;
    if (constraint instanceof ForeignKey) {
        if (tableConfig.getColumnNamesIsNoFK().contains(constraint.getColumn(0).getName().toLowerCase())) {
            return "-- skipped creation of foreign key constraint '" + name + "' for table '" + table.getName()
                    + "' according to annotation of type " + NoForeignKeyConstraint.class.getSimpleName();
        }
        refTblNameLC = getProfile().getNamingStrategy()
                .tableName(((ForeignKey) constraint).getReferencedTable().getName()).toLowerCase();
    }

    checkObjectName(dialect, name);
    String i18nFK = tableConfig.getI18nBaseEntityFkCol();

    if (i18nFK != null) {
        StringBuilder sql = new StringBuilder();
        tableNameLC = getI18NDetailTableName(tableNameLC);
        Matcher matcher = TBL_ALTER_PATTERN.matcher(buf.toString());
        if (matcher.find()) {
            sql.append(buf.substring(0, matcher.start(1))).append(tableNameLC)
                    .append(buf.substring(matcher.end(1)));
        }
        buf = new StringBuffer(sql.toString());
    }

    if (constraint instanceof ForeignKey) {
        StringBuilder colList = new StringBuilder();
        org.hibernate.mapping.Column singleColumn = null;

        TableConfig refTableConfig = tblNameToConfig.get(refTblNameLC);
        IntervalPartitioning refTblPart = refTableConfig != null
                ? refTableConfig.getTableAnnotationOfType(IntervalPartitioning.class)
                : null;

        for (org.hibernate.mapping.Column column : (Iterable<? extends org.hibernate.mapping.Column>) constraint
                .getColumns()) {
            if (colList.length() > 0) {
                colList.append(", ");
            }
            colList.append(column.getName().toLowerCase());
            singleColumn = singleColumn == null ? column : null;
        }

        if (externalViews.contains(refTblNameLC)) {
            buf = new StringBuffer("-- skipped creation of constraint '" + name + "' on table '" + tableNameLC
                    + "' since a view will be referenced");
        } else if (refTblPart != null && refTblPart.useLocalPK() && supportsPartitioning(dialect)) {
            buf = new StringBuffer();
            buf.append("-- skipped creation of foreign key constraint '").append(name).append("' on table '")
                    .append(tableNameLC).append("' to table '").append(refTblNameLC)
                    .append("' as the partitioned target table has a local PK (see @IntervalPartitioning on ")
                    .append(((ForeignKey) constraint).getReferencedEntityName()).append(")");
        } else {
            if (singleColumn != null) {
                if (tableConfig.getColumnNamesIsCascadeNullable()
                        .contains(singleColumn.getName().toLowerCase())) {
                    buf.append(" on delete set null");
                } else if (tableConfig.getColumnNamesIsCascadeDelete()
                        .contains(singleColumn.getName().toLowerCase()) && buf.indexOf("on delete") < 0) {
                    buf.append(" on delete cascade");
                }
            }

            Map<String, Deferrable> col2Deferrable = tableConfig.getColumnNameToDeferrable();
            Deferrable deferrable;
            if (supportsDeferrable(dialect) && col2Deferrable != null
                    && (deferrable = col2Deferrable.get(colList.toString())) != null) {
                buf.append(" deferrable");
                if (deferrable.initiallyDeferred()) {
                    buf.append(" initially deferred");
                }
            }

            if (getProfile().isDisableFKs()) {
                buf.insert(0,
                        "-- creating FK constraint initially disabled since we do not need it for profile '"
                                + getProfile() + "'\n");
                buf.append(" disable");
            }
        }

        getProfile().duplex(ObjectType.CONSTRAINT, name, buf.toString());

        if (constraint.getColumnSpan() == 1 && hasIndex(table, tableNameLC, singleColumn)) {
            LOG.debug("not creating foreign key index as there is already an index on table " + tableNameLC
                    + " and column " + colList.toString());
        } else {
            String fkIndexName = getProfile().getNamingStrategy().indexName(getEntityClassName(tableNameLC),
                    tableNameLC, DefaultNamingStrategy.concatColumnNames(colList.toString()));
            StringBuilder objDdl = new StringBuilder();
            objDdl.append("create index ").append(fkIndexName).append(" on ").append(tableNameLC).append(" (")
                    .append(colList.toString()).append(")");

            if (constraint.getColumnSpan() == 1) {
                tblColNameHasSingleColIndex.add(tableNameLC + "." + colList.toString());
            }

            buf.append(STATEMENT_SEPARATOR).append(objDdl);

            getProfile().duplex(ObjectType.INDEX, fkIndexName, objDdl.toString());
        }
    }

    return buf.toString();
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

License:Apache License

public String updateCreateIndex(Dialect dialect, StringBuffer buf, String name, Table table,
        List<org.hibernate.mapping.Column> columns) {
    String newName = getProfile().getNamingStrategy().indexName(name);

    if (!name.equals(newName)) {
        Matcher matcher = IDX_CREATE_PATTERN.matcher(buf.toString());
        if (matcher.find()) {
            StringBuilder builder = new StringBuilder();
            builder.append(buf.substring(0, matcher.start(2)));
            builder.append(newName);//from  w  w  w . j  av  a  2 s.c o  m
            builder.append(buf.substring(matcher.end(2)));
            buf = new StringBuffer(builder.toString());
        }
        name = newName;
    }

    String tableNameLC = getProfile().getNamingStrategy().tableName(table.getName()).toLowerCase();
    if (!renderTable(tableNameLC)) {
        return "-- skipped creation of index '" + name + "' for table '" + tableNameLC
                + "' as the mapped entity was not chosen to be processed";
    }

    if (externalViews.contains(tableNameLC)) {
        return "-- skipped creation of index '" + name + "' on table '" + tableNameLC
                + "' since there is a view in place";
    }
    TableConfig tableConfig = tblNameToConfig.get(tableNameLC);

    checkObjectName(dialect, name);

    IntervalPartitioning partitioning = tableConfig.getTableAnnotationOfType(IntervalPartitioning.class);
    if (partitioning != null && supportsPartitioning(dialect)) {
        Matcher matcher = IDX_CREATE_PATTERN.matcher(buf.toString());
        // find create index and define local not for unique indexes
        if (matcher.find() && matcher.group(1) == null) {
            buf.append(" local");
        }
    }

    String i18nFK = tableConfig.getI18nBaseEntityFkCol();

    if (i18nFK != null) {
        StringBuilder sql = new StringBuilder();
        String i18nTblName = getI18NDetailTableName(tableNameLC);

        if (columns.size() == 1) {
            if (hasIndex(table, i18nTblName, columns.get(0))) {
                return "-- table " + i18nTblName + " already has an index on column "
                        + columns.get(0).getName();
            }
            tblColNameHasSingleColIndex.add(i18nTblName + "." + columns.get(0).getName().toLowerCase());
        }

        Matcher matcher = IDX_CREATE_PATTERN.matcher(buf.toString());
        if (matcher.find()) {
            sql.append(buf.substring(0, matcher.start(3))).append(i18nTblName)
                    .append(buf.substring(matcher.end(3)));
        }

        getProfile().duplex(ObjectType.INDEX, name, sql.toString());

        return sql.toString();
    }

    if (columns.size() == 1) {
        if (hasIndex(table, tableNameLC, columns.get(0))) {
            return "-- table " + table.getName() + " already has an index on column "
                    + columns.get(0).getName();
        }

        tblColNameHasSingleColIndex.add(tableNameLC + "." + columns.get(0).getName().toLowerCase());
    }

    getProfile().duplex(ObjectType.INDEX, name, buf.toString());

    return buf.toString();
}