From 3fb9577e500d4331741c37f23c66737d96b8c272 Mon Sep 17 00:00:00 2001 From: Andrea Boriero Date: Thu, 7 Jan 2016 14:30:31 +0000 Subject: [PATCH] HHH-10425 - Fix SchemaMigration creates foreign keys too early if across schema --- .../tool/schema/internal/SchemaMigratorImpl.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaMigratorImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaMigratorImpl.java index 6388ffd977..5386f84a12 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaMigratorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaMigratorImpl.java @@ -183,7 +183,6 @@ public class SchemaMigratorImpl implements SchemaMigrator { applyIndexes( table, tableInformation, metadata, targets ); applyUniqueKeys( table, tableInformation, metadata, targets ); - applyForeignKeys( table, tableInformation, metadata, targets ); } for ( Sequence sequence : namespace.getSequences() ) { @@ -205,6 +204,17 @@ public class SchemaMigratorImpl implements SchemaMigrator { } } + //NOTE : Foreign keys must be created *after* all tables of all namespaces for cross namespace fks. see HHH-10420 + for ( Namespace namespace : database.getNamespaces() ) { + for ( Table table : namespace.getTables() ) { + final TableInformation tableInformation = existingDatabase.getTableInformation( table.getQualifiedTableName() ); + if ( tableInformation != null && !tableInformation.isPhysicalTable() ) { + continue; + } + applyForeignKeys( table, tableInformation, metadata, targets ); + } + } + // Create after-table AuxiliaryDatabaseObjects for ( AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects() ) { if ( !auxiliaryDatabaseObject.beforeTablesOnCreation() ) {