@@ -1075,9 +1075,17 @@ public String[] generateSchemaCreationScript(Dialect dialect) throws HibernateEx
10751075 )
10761076 );
10771077 }
1078+ }
1079+ }
1080+
1081+ // Foreign keys must be created *after* unique keys for numerous DBs. See HH-8390.
1082+ iter = getTableMappings ();
1083+ while ( iter .hasNext () ) {
1084+ Table table = (Table ) iter .next ();
1085+ if ( table .isPhysicalTable () ) {
10781086
10791087 if ( dialect .hasAlterTable () ) {
1080- subIter = table .getForeignKeyIterator ();
1088+ Iterator subIter = table .getForeignKeyIterator ();
10811089 while ( subIter .hasNext () ) {
10821090 ForeignKey fk = (ForeignKey ) subIter .next ();
10831091 if ( fk .isPhysicalConstraint () ) {
@@ -1215,6 +1223,33 @@ public List<SchemaUpdateScript> generateSchemaUpdateScriptList(Dialect dialect,
12151223 }
12161224 }
12171225
1226+ Iterator subIter = table .getIndexIterator ();
1227+ while ( subIter .hasNext () ) {
1228+ final Index index = (Index ) subIter .next ();
1229+ // Skip if index already exists
1230+ if ( tableInfo != null && StringHelper .isNotEmpty ( index .getName () ) ) {
1231+ final IndexMetadata meta = tableInfo .getIndexMetadata ( index .getName () );
1232+ if ( meta != null ) {
1233+ continue ;
1234+ }
1235+ }
1236+ scripts .add ( new SchemaUpdateScript ( index .sqlCreateString ( dialect , mapping , tableCatalog ,
1237+ tableSchema ), false ) );
1238+ }
1239+ }
1240+ }
1241+
1242+ // Foreign keys must be created *after* unique keys for numerous DBs. See HH-8390.
1243+ iter = getTableMappings ();
1244+ while ( iter .hasNext () ) {
1245+ Table table = (Table ) iter .next ();
1246+ String tableSchema = ( table .getSchema () == null ) ? defaultSchema : table .getSchema ();
1247+ String tableCatalog = ( table .getCatalog () == null ) ? defaultCatalog : table .getCatalog ();
1248+ if ( table .isPhysicalTable () ) {
1249+
1250+ TableMetadata tableInfo = databaseMetadata .getTableMetadata ( table .getName (), tableSchema ,
1251+ tableCatalog , table .isQuoted () );
1252+
12181253 if ( dialect .hasAlterTable () ) {
12191254 Iterator subIter = table .getForeignKeyIterator ();
12201255 while ( subIter .hasNext () ) {
@@ -1230,20 +1265,6 @@ public List<SchemaUpdateScript> generateSchemaUpdateScriptList(Dialect dialect,
12301265 }
12311266 }
12321267 }
1233-
1234- Iterator subIter = table .getIndexIterator ();
1235- while ( subIter .hasNext () ) {
1236- final Index index = (Index ) subIter .next ();
1237- // Skip if index already exists
1238- if ( tableInfo != null && StringHelper .isNotEmpty ( index .getName () ) ) {
1239- final IndexMetadata meta = tableInfo .getIndexMetadata ( index .getName () );
1240- if ( meta != null ) {
1241- continue ;
1242- }
1243- }
1244- scripts .add ( new SchemaUpdateScript ( index .sqlCreateString ( dialect , mapping , tableCatalog ,
1245- tableSchema ), false ) );
1246- }
12471268 }
12481269 }
12491270
0 commit comments