Search in sources :

Example 6 with UniqueKey

use of org.hibernate.mapping.UniqueKey in project hibernate-orm by hibernate.

the class InFlightMetadataCollectorImpl method buildUniqueKeyFromColumnNames.

private void buildUniqueKeyFromColumnNames(final Table table, String keyName, final String[] columnNames, String[] orderings, boolean unique, final MetadataBuildingContext buildingContext) {
    int size = columnNames.length;
    Column[] columns = new Column[size];
    Set<Column> unbound = new HashSet<Column>();
    Set<Column> unboundNoLogical = new HashSet<Column>();
    for (int index = 0; index < size; index++) {
        final String logicalColumnName = columnNames[index];
        try {
            final String physicalColumnName = getPhysicalColumnName(table, logicalColumnName);
            columns[index] = new Column(physicalColumnName);
            unbound.add(columns[index]);
        //column equals and hashcode is based on column name
        } catch (MappingException e) {
            // If at least 1 columnName does exist, 'columns' will contain a mix of Columns and nulls.  In order
            // to exhaustively report all of the unbound columns at once, w/o an NPE in
            // Constraint#generateName's array sorting, simply create a fake Column.
            columns[index] = new Column(logicalColumnName);
            unboundNoLogical.add(columns[index]);
        }
    }
    final String originalKeyName = keyName;
    if (unique) {
        final Identifier keyNameIdentifier = getMetadataBuildingOptions().getImplicitNamingStrategy().determineUniqueKeyName(new ImplicitUniqueKeyNameSource() {

            @Override
            public MetadataBuildingContext getBuildingContext() {
                return buildingContext;
            }

            @Override
            public Identifier getTableName() {
                return table.getNameIdentifier();
            }

            private List<Identifier> columnNameIdentifiers;

            @Override
            public List<Identifier> getColumnNames() {
                // be lazy about building these
                if (columnNameIdentifiers == null) {
                    columnNameIdentifiers = toIdentifiers(columnNames);
                }
                return columnNameIdentifiers;
            }

            @Override
            public Identifier getUserProvidedIdentifier() {
                return originalKeyName != null ? Identifier.toIdentifier(originalKeyName) : null;
            }
        });
        keyName = keyNameIdentifier.render(getDatabase().getJdbcEnvironment().getDialect());
        UniqueKey uk = table.getOrCreateUniqueKey(keyName);
        for (int i = 0; i < columns.length; i++) {
            Column column = columns[i];
            String order = orderings != null ? orderings[i] : null;
            if (table.containsColumn(column)) {
                uk.addColumn(column, order);
                unbound.remove(column);
            }
        }
    } else {
        final Identifier keyNameIdentifier = getMetadataBuildingOptions().getImplicitNamingStrategy().determineIndexName(new ImplicitIndexNameSource() {

            @Override
            public MetadataBuildingContext getBuildingContext() {
                return buildingContext;
            }

            @Override
            public Identifier getTableName() {
                return table.getNameIdentifier();
            }

            private List<Identifier> columnNameIdentifiers;

            @Override
            public List<Identifier> getColumnNames() {
                // be lazy about building these
                if (columnNameIdentifiers == null) {
                    columnNameIdentifiers = toIdentifiers(columnNames);
                }
                return columnNameIdentifiers;
            }

            @Override
            public Identifier getUserProvidedIdentifier() {
                return originalKeyName != null ? Identifier.toIdentifier(originalKeyName) : null;
            }
        });
        keyName = keyNameIdentifier.render(getDatabase().getJdbcEnvironment().getDialect());
        Index index = table.getOrCreateIndex(keyName);
        for (int i = 0; i < columns.length; i++) {
            Column column = columns[i];
            String order = orderings != null ? orderings[i] : null;
            if (table.containsColumn(column)) {
                index.addColumn(column, order);
                unbound.remove(column);
            }
        }
    }
    if (unbound.size() > 0 || unboundNoLogical.size() > 0) {
        StringBuilder sb = new StringBuilder("Unable to create ");
        if (unique) {
            sb.append("unique key constraint (");
        } else {
            sb.append("index (");
        }
        for (String columnName : columnNames) {
            sb.append(columnName).append(", ");
        }
        sb.setLength(sb.length() - 2);
        sb.append(") on table ").append(table.getName()).append(": database column ");
        for (Column column : unbound) {
            sb.append("'").append(column.getName()).append("', ");
        }
        for (Column column : unboundNoLogical) {
            sb.append("'").append(column.getName()).append("', ");
        }
        sb.setLength(sb.length() - 2);
        sb.append(" not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)");
        throw new AnnotationException(sb.toString());
    }
}
Also used : MetadataBuildingContext(org.hibernate.boot.spi.MetadataBuildingContext) LocalMetadataBuildingContext(org.hibernate.boot.model.source.spi.LocalMetadataBuildingContext) Index(org.hibernate.mapping.Index) DuplicateMappingException(org.hibernate.DuplicateMappingException) MappingException(org.hibernate.MappingException) Identifier(org.hibernate.boot.model.naming.Identifier) ImplicitIndexNameSource(org.hibernate.boot.model.naming.ImplicitIndexNameSource) Column(org.hibernate.mapping.Column) UniqueKey(org.hibernate.mapping.UniqueKey) AnnotationException(org.hibernate.AnnotationException) List(java.util.List) ArrayList(java.util.ArrayList) ImplicitUniqueKeyNameSource(org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource) HashSet(java.util.HashSet)

Example 7 with UniqueKey

use of org.hibernate.mapping.UniqueKey in project hibernate-orm by hibernate.

the class AbstractSchemaMigrator method applyUniqueKeys.

protected void applyUniqueKeys(Table table, TableInformation tableInfo, Dialect dialect, Metadata metadata, Formatter formatter, ExecutionOptions options, GenerationTarget... targets) {
    if (uniqueConstraintStrategy == null) {
        uniqueConstraintStrategy = determineUniqueConstraintSchemaUpdateStrategy(metadata);
    }
    if (uniqueConstraintStrategy != UniqueConstraintSchemaUpdateStrategy.SKIP) {
        final Exporter<Constraint> exporter = dialect.getUniqueKeyExporter();
        final Iterator ukItr = table.getUniqueKeyIterator();
        while (ukItr.hasNext()) {
            final UniqueKey uniqueKey = (UniqueKey) ukItr.next();
            // Skip if index already exists. Most of the time, this
            // won't work since most Dialects use Constraints. However,
            // keep it for the few that do use Indexes.
            IndexInformation indexInfo = null;
            if (tableInfo != null && StringHelper.isNotEmpty(uniqueKey.getName())) {
                indexInfo = tableInfo.getIndex(Identifier.toIdentifier(uniqueKey.getName()));
            }
            if (indexInfo == null) {
                if (uniqueConstraintStrategy == UniqueConstraintSchemaUpdateStrategy.DROP_RECREATE_QUIETLY) {
                    applySqlStrings(true, exporter.getSqlDropStrings(uniqueKey, metadata), formatter, options, targets);
                }
                applySqlStrings(true, exporter.getSqlCreateStrings(uniqueKey, metadata), formatter, options, targets);
            }
        }
    }
}
Also used : IndexInformation(org.hibernate.tool.schema.extract.spi.IndexInformation) Constraint(org.hibernate.mapping.Constraint) UniqueKey(org.hibernate.mapping.UniqueKey) Iterator(java.util.Iterator)

Example 8 with UniqueKey

use of org.hibernate.mapping.UniqueKey in project hibernate-orm by hibernate.

the class AbstractJPAIndexTest method testTableIndex.

@Test
public void testTableIndex() {
    PersistentClass entity = metadata().getEntityBinding(Car.class.getName());
    Iterator itr = entity.getTable().getUniqueKeyIterator();
    assertTrue(itr.hasNext());
    UniqueKey uk = (UniqueKey) itr.next();
    assertFalse(itr.hasNext());
    assertTrue(StringHelper.isNotEmpty(uk.getName()));
    assertEquals(2, uk.getColumnSpan());
    Column column = (Column) uk.getColumns().get(0);
    assertEquals("brand", column.getName());
    column = (Column) uk.getColumns().get(1);
    assertEquals("producer", column.getName());
    assertSame(entity.getTable(), uk.getTable());
    itr = entity.getTable().getIndexIterator();
    assertTrue(itr.hasNext());
    Index index = (Index) itr.next();
    assertFalse(itr.hasNext());
    assertEquals("Car_idx", index.getName());
    assertEquals(1, index.getColumnSpan());
    column = index.getColumnIterator().next();
    assertEquals("since", column.getName());
    assertSame(entity.getTable(), index.getTable());
}
Also used : UniqueKey(org.hibernate.mapping.UniqueKey) Column(org.hibernate.mapping.Column) Iterator(java.util.Iterator) Index(org.hibernate.mapping.Index) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Example 9 with UniqueKey

use of org.hibernate.mapping.UniqueKey in project uPortal by Jasig.

the class HibernateDbLoader method createScript.

/** 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));
        }
    }
    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;
}
Also used : Table(org.hibernate.mapping.Table) UniqueKey(org.hibernate.mapping.UniqueKey) ArrayList(java.util.ArrayList) Index(org.hibernate.mapping.Index) ForeignKey(org.hibernate.mapping.ForeignKey)

Example 10 with UniqueKey

use of org.hibernate.mapping.UniqueKey in project uPortal by Jasig.

the class TableXmlHandler method startElement.

/* (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
    if ("table".equals(name)) {
        this.currentColumns = new LinkedHashMap<String, Column>();
        this.currentColumnTypes = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
    } else if ("index".equals(name)) {
        this.currentIndex = new Index();
        this.currentIndex.setTable(this.currentTable);
    } else if ("unique".equals(name)) {
        this.currentUnique = new UniqueKey();
        this.currentUnique.setTable(this.currentTable);
    }
    this.chars = new StringBuilder();
}
Also used : Column(org.hibernate.mapping.Column) UniqueKey(org.hibernate.mapping.UniqueKey) Index(org.hibernate.mapping.Index)

Aggregations

UniqueKey (org.hibernate.mapping.UniqueKey)10 Iterator (java.util.Iterator)5 Column (org.hibernate.mapping.Column)5 Index (org.hibernate.mapping.Index)5 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 ForeignKey (org.hibernate.mapping.ForeignKey)3 HashSet (java.util.HashSet)2 Identifier (org.hibernate.boot.model.naming.Identifier)2 Namespace (org.hibernate.boot.model.relational.Namespace)2 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)2 Table (org.hibernate.mapping.Table)2 TestForIssue (org.hibernate.testing.TestForIssue)2 List (java.util.List)1 ForeignKey (javax.persistence.ForeignKey)1 JoinColumn (javax.persistence.JoinColumn)1 UniqueConstraint (javax.persistence.UniqueConstraint)1 AnnotationException (org.hibernate.AnnotationException)1 DuplicateMappingException (org.hibernate.DuplicateMappingException)1 MappingException (org.hibernate.MappingException)1