Search in sources :

Example 1 with ForeignKey

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

the class SchemaCreatorImpl method createFromMetadata.

public void createFromMetadata(Metadata metadata, ExecutionOptions options, Dialect dialect, Formatter formatter, GenerationTarget... targets) {
    boolean tryToCreateCatalogs = false;
    boolean tryToCreateSchemas = false;
    if (options.shouldManageNamespaces()) {
        if (dialect.canCreateSchema()) {
            tryToCreateSchemas = true;
        }
        if (dialect.canCreateCatalog()) {
            tryToCreateCatalogs = true;
        }
    }
    final Database database = metadata.getDatabase();
    final JdbcEnvironment jdbcEnvironment = database.getJdbcEnvironment();
    final Set<String> exportIdentifiers = new HashSet<String>(50);
    // first, create each catalog/schema
    if (tryToCreateCatalogs || tryToCreateSchemas) {
        Set<Identifier> exportedCatalogs = new HashSet<Identifier>();
        for (Namespace namespace : database.getNamespaces()) {
            if (!schemaFilter.includeNamespace(namespace)) {
                continue;
            }
            if (tryToCreateCatalogs) {
                final Identifier catalogLogicalName = namespace.getName().getCatalog();
                final Identifier catalogPhysicalName = namespace.getPhysicalName().getCatalog();
                if (catalogPhysicalName != null && !exportedCatalogs.contains(catalogLogicalName)) {
                    applySqlStrings(dialect.getCreateCatalogCommand(catalogPhysicalName.render(dialect)), formatter, options, targets);
                    exportedCatalogs.add(catalogLogicalName);
                }
            }
            if (tryToCreateSchemas && namespace.getPhysicalName().getSchema() != null) {
                applySqlStrings(dialect.getCreateSchemaCommand(namespace.getPhysicalName().getSchema().render(dialect)), formatter, options, targets);
            }
        }
    }
    // next, create all "beforeQuery table" auxiliary objects
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (!auxiliaryDatabaseObject.beforeTablesOnCreation()) {
            continue;
        }
        if (auxiliaryDatabaseObject.appliesToDialect(dialect)) {
            checkExportIdentifier(auxiliaryDatabaseObject, exportIdentifiers);
            applySqlStrings(dialect.getAuxiliaryDatabaseObjectExporter().getSqlCreateStrings(auxiliaryDatabaseObject, metadata), formatter, options, targets);
        }
    }
    // then, create all schema objects (tables, sequences, constraints, etc) in each schema
    for (Namespace namespace : database.getNamespaces()) {
        if (!schemaFilter.includeNamespace(namespace)) {
            continue;
        }
        // sequences
        for (Sequence sequence : namespace.getSequences()) {
            if (!schemaFilter.includeSequence(sequence)) {
                continue;
            }
            checkExportIdentifier(sequence, exportIdentifiers);
            applySqlStrings(dialect.getSequenceExporter().getSqlCreateStrings(sequence, metadata), //						),
            formatter, options, targets);
        }
        // tables
        for (Table table : namespace.getTables()) {
            if (!table.isPhysicalTable()) {
                continue;
            }
            if (!schemaFilter.includeTable(table)) {
                continue;
            }
            checkExportIdentifier(table, exportIdentifiers);
            applySqlStrings(dialect.getTableExporter().getSqlCreateStrings(table, metadata), formatter, options, targets);
        }
        for (Table table : namespace.getTables()) {
            if (!table.isPhysicalTable()) {
                continue;
            }
            if (!schemaFilter.includeTable(table)) {
                continue;
            }
            // indexes
            final Iterator indexItr = table.getIndexIterator();
            while (indexItr.hasNext()) {
                final Index index = (Index) indexItr.next();
                checkExportIdentifier(index, exportIdentifiers);
                applySqlStrings(dialect.getIndexExporter().getSqlCreateStrings(index, metadata), formatter, options, targets);
            }
            // unique keys
            final Iterator ukItr = table.getUniqueKeyIterator();
            while (ukItr.hasNext()) {
                final UniqueKey uniqueKey = (UniqueKey) ukItr.next();
                checkExportIdentifier(uniqueKey, exportIdentifiers);
                applySqlStrings(dialect.getUniqueKeyExporter().getSqlCreateStrings(uniqueKey, metadata), formatter, options, targets);
            }
        }
    }
    //NOTE : Foreign keys must be created *afterQuery* all tables of all namespaces for cross namespace fks. see HHH-10420
    for (Namespace namespace : database.getNamespaces()) {
        if (!schemaFilter.includeNamespace(namespace)) {
            continue;
        }
        for (Table table : namespace.getTables()) {
            if (!schemaFilter.includeTable(table)) {
                continue;
            }
            // foreign keys
            final Iterator fkItr = table.getForeignKeyIterator();
            while (fkItr.hasNext()) {
                final ForeignKey foreignKey = (ForeignKey) fkItr.next();
                applySqlStrings(dialect.getForeignKeyExporter().getSqlCreateStrings(foreignKey, metadata), formatter, options, targets);
            }
        }
    }
    // next, create all "afterQuery table" auxiliary objects
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (auxiliaryDatabaseObject.appliesToDialect(dialect) && !auxiliaryDatabaseObject.beforeTablesOnCreation()) {
            checkExportIdentifier(auxiliaryDatabaseObject, exportIdentifiers);
            applySqlStrings(dialect.getAuxiliaryDatabaseObjectExporter().getSqlCreateStrings(auxiliaryDatabaseObject, metadata), formatter, options, targets);
        }
    }
    // and finally add all init commands
    for (InitCommand initCommand : database.getInitCommands()) {
        // todo: this should alo probably use the DML formatter...
        applySqlStrings(initCommand.getInitCommands(), formatter, options, targets);
    }
}
Also used : Table(org.hibernate.mapping.Table) InitCommand(org.hibernate.boot.model.relational.InitCommand) Index(org.hibernate.mapping.Index) AuxiliaryDatabaseObject(org.hibernate.boot.model.relational.AuxiliaryDatabaseObject) Sequence(org.hibernate.boot.model.relational.Sequence) ForeignKey(org.hibernate.mapping.ForeignKey) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) Namespace(org.hibernate.boot.model.relational.Namespace) Identifier(org.hibernate.boot.model.naming.Identifier) UniqueKey(org.hibernate.mapping.UniqueKey) Database(org.hibernate.boot.model.relational.Database) Iterator(java.util.Iterator) HashSet(java.util.HashSet)

Example 2 with ForeignKey

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

the class DefaultNamingCollectionElementTest method checkDefaultJoinColumnName.

protected void checkDefaultJoinColumnName(Class<?> ownerEntityClass, String ownerCollectionPropertyName, String ownerForeignKeyNameExpected) {
    final org.hibernate.mapping.Collection ownerCollection = metadata().getCollectionBinding(ownerEntityClass.getName() + '.' + ownerCollectionPropertyName);
    // The default owner join column can only be computed if it has a PK with 1 column.
    assertEquals(1, ownerCollection.getOwner().getKey().getColumnSpan());
    assertEquals(ownerForeignKeyNameExpected, ownerCollection.getKey().getColumnIterator().next().getText());
    boolean hasOwnerFK = false;
    for (Iterator it = ownerCollection.getCollectionTable().getForeignKeyIterator(); it.hasNext(); ) {
        final ForeignKey fk = (ForeignKey) it.next();
        assertSame(ownerCollection.getCollectionTable(), fk.getTable());
        if (fk.getColumnSpan() > 1) {
            continue;
        }
        if (fk.getColumn(0).getText().equals(ownerForeignKeyNameExpected)) {
            assertSame(ownerCollection.getOwner().getTable(), fk.getReferencedTable());
            hasOwnerFK = true;
        }
    }
    assertTrue(hasOwnerFK);
}
Also used : Iterator(java.util.Iterator) Collection(org.hibernate.mapping.Collection) ForeignKey(org.hibernate.mapping.ForeignKey)

Example 3 with ForeignKey

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

the class ManyToManyImplicitNamingTest method checkDefaultJoinTablAndJoinColumnNames.

protected void checkDefaultJoinTablAndJoinColumnNames(Class<?> ownerEntityClass, String ownerCollectionPropertyName, String inverseCollectionPropertyName, String expectedCollectionTableName, String ownerForeignKeyNameExpected, String inverseForeignKeyNameExpected) {
    final org.hibernate.mapping.Collection collection = metadata().getCollectionBinding(ownerEntityClass.getName() + '.' + ownerCollectionPropertyName);
    final org.hibernate.mapping.Table table = collection.getCollectionTable();
    assertEquals(expectedCollectionTableName, table.getName());
    final org.hibernate.mapping.Collection ownerCollection = metadata().getCollectionBinding(ownerEntityClass.getName() + '.' + ownerCollectionPropertyName);
    // The default owner and inverse join columns can only be computed if they have PK with 1 column.
    assertEquals(1, ownerCollection.getOwner().getKey().getColumnSpan());
    assertEquals(ownerForeignKeyNameExpected, ownerCollection.getKey().getColumnIterator().next().getText());
    final EntityType associatedEntityType = (EntityType) ownerCollection.getElement().getType();
    final PersistentClass associatedPersistentClass = metadata().getEntityBinding(associatedEntityType.getAssociatedEntityName());
    assertEquals(1, associatedPersistentClass.getKey().getColumnSpan());
    if (inverseCollectionPropertyName != null) {
        final org.hibernate.mapping.Collection inverseCollection = metadata().getCollectionBinding(associatedPersistentClass.getEntityName() + '.' + inverseCollectionPropertyName);
        assertEquals(inverseForeignKeyNameExpected, inverseCollection.getKey().getColumnIterator().next().getText());
    }
    boolean hasOwnerFK = false;
    boolean hasInverseFK = false;
    for (Iterator it = ownerCollection.getCollectionTable().getForeignKeyIterator(); it.hasNext(); ) {
        final ForeignKey fk = (ForeignKey) it.next();
        assertSame(ownerCollection.getCollectionTable(), fk.getTable());
        if (fk.getColumnSpan() > 1) {
            continue;
        }
        if (fk.getColumn(0).getText().equals(ownerForeignKeyNameExpected)) {
            assertSame(ownerCollection.getOwner().getTable(), fk.getReferencedTable());
            hasOwnerFK = true;
        } else if (fk.getColumn(0).getText().equals(inverseForeignKeyNameExpected)) {
            assertSame(associatedPersistentClass.getTable(), fk.getReferencedTable());
            hasInverseFK = true;
        }
    }
    assertTrue(hasOwnerFK);
    assertTrue(hasInverseFK);
}
Also used : EntityType(org.hibernate.type.EntityType) Iterator(java.util.Iterator) ForeignKey(org.hibernate.mapping.ForeignKey) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 4 with ForeignKey

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

the class ConstraintTest method testConstraintNameLength.

@Test
@TestForIssue(jiraKey = "HHH-1904")
public void testConstraintNameLength() {
    int foundCount = 0;
    for (Namespace namespace : metadata().getDatabase().getNamespaces()) {
        for (org.hibernate.mapping.Table table : namespace.getTables()) {
            Iterator fkItr = table.getForeignKeyIterator();
            while (fkItr.hasNext()) {
                ForeignKey fk = (ForeignKey) fkItr.next();
                assertTrue(fk.getName().length() <= MAX_NAME_LENGTH);
                // ensure the randomly generated constraint name doesn't
                // happen if explicitly given
                Column column = fk.getColumn(0);
                if (column.getName().equals("explicit_native")) {
                    foundCount++;
                    assertEquals(fk.getName(), EXPLICIT_FK_NAME_NATIVE);
                } else if (column.getName().equals("explicit_jpa")) {
                    foundCount++;
                    assertEquals(fk.getName(), EXPLICIT_FK_NAME_JPA);
                }
            }
            Iterator ukItr = table.getUniqueKeyIterator();
            while (ukItr.hasNext()) {
                UniqueKey uk = (UniqueKey) ukItr.next();
                assertTrue(uk.getName().length() <= MAX_NAME_LENGTH);
                // ensure the randomly generated constraint name doesn't
                // happen if explicitly given
                Column column = uk.getColumn(0);
                if (column.getName().equals("explicit")) {
                    foundCount++;
                    assertEquals(uk.getName(), EXPLICIT_UK_NAME);
                }
            }
        }
    }
    assertEquals("Could not find the necessary columns.", 3, foundCount);
}
Also used : JoinColumn(javax.persistence.JoinColumn) Column(org.hibernate.mapping.Column) UniqueKey(org.hibernate.mapping.UniqueKey) Iterator(java.util.Iterator) ForeignKey(org.hibernate.mapping.ForeignKey) UniqueConstraint(javax.persistence.UniqueConstraint) Namespace(org.hibernate.boot.model.relational.Namespace) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 5 with ForeignKey

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

the class PropertyRefTest method testForeignKeyCreation.

@Test
public void testForeignKeyCreation() {
    PersistentClass classMapping = metadata().getEntityBinding(Account.class.getName());
    Iterator foreignKeyIterator = classMapping.getTable().getForeignKeyIterator();
    boolean found = false;
    while (foreignKeyIterator.hasNext()) {
        ForeignKey element = (ForeignKey) foreignKeyIterator.next();
        if (element.getReferencedEntityName().equals(Person.class.getName())) {
            if (!element.isReferenceToPrimaryKey()) {
                List referencedColumns = element.getReferencedColumns();
                Column column = (Column) referencedColumns.get(0);
                if (column.getName().equals("person_userid")) {
                    // extend test to include the columns
                    found = true;
                }
            }
        }
    }
    assertTrue("Property ref foreign key not found", found);
}
Also used : Column(org.hibernate.mapping.Column) Iterator(java.util.Iterator) List(java.util.List) ForeignKey(org.hibernate.mapping.ForeignKey) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Aggregations

ForeignKey (org.hibernate.mapping.ForeignKey)11 Iterator (java.util.Iterator)7 Table (org.hibernate.mapping.Table)5 PersistentClass (org.hibernate.mapping.PersistentClass)3 UniqueKey (org.hibernate.mapping.UniqueKey)3 Test (org.junit.Test)3 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Identifier (org.hibernate.boot.model.naming.Identifier)2 Namespace (org.hibernate.boot.model.relational.Namespace)2 Column (org.hibernate.mapping.Column)2 Index (org.hibernate.mapping.Index)2 TestForIssue (org.hibernate.testing.TestForIssue)2 Map (java.util.Map)1 JoinColumn (javax.persistence.JoinColumn)1 UniqueConstraint (javax.persistence.UniqueConstraint)1 DuplicateMappingException (org.hibernate.DuplicateMappingException)1 MappingException (org.hibernate.MappingException)1 MetadataSources (org.hibernate.boot.MetadataSources)1