This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch 9.0.x-h7-improvement-phase3 in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit fbcf641e6f80abcb0d32bd73518a74d9a1a4728c Author: Walter Duque de Estrada <[email protected]> AuthorDate: Tue Oct 6 19:38:16 2026 -0500 fix: create the table of a table id generator before the columns are ordered in generated mode The domain binder's metadata build creates the id generator of every root once, so a table generator registers its table (hibernate_sequences) before Hibernate orders every table's columns by size and name: next_val, sequence_name. The generated mode installs its generators only after the metadata is built, so the table was registered when the persisters were built, after the ordering, and kept the generator's own order (sequence_name, next_val). The binder now creates the identifier generators of the roots once the generators are installed, as Hibernate does while it builds the metadata, so a database created in generated mode has the same column order as one created with the domain binder. Hibernate's legacy column ordering strategy was tried and is not the answer: the domain binder's tables are ordered by the standard strategy too, so legacy changes the column order of 819 tables the two modes agreed on (819 differences in the DDL differential). Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../jpa/GeneratedDomainClassBinder.groovy | 50 ++++++++++++++++++++++ .../generated/GeneratedDomainClassesDdlSpec.groovy | 26 ++++++++++- ...eneratedDomainClassesDdlDifferentialSpec.groovy | 2 +- 3 files changed, 76 insertions(+), 2 deletions(-) diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy index 816385c27c..0198b6cbd3 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy @@ -25,12 +25,18 @@ import org.hibernate.MappingException import org.hibernate.boot.SessionFactoryBuilder import org.hibernate.boot.internal.InFlightMetadataCollectorImpl import org.hibernate.boot.internal.MetadataBuildingContextRootImpl +import org.hibernate.boot.model.relational.Database +import org.hibernate.boot.model.relational.SqlStringGenerationContext +import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl import org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl import org.hibernate.boot.spi.AdditionalMappingContributions import org.hibernate.boot.spi.MetadataBuildingContext import org.hibernate.boot.spi.MetadataImplementor import org.hibernate.boot.spi.SessionFactoryBuilderFactory import org.hibernate.boot.spi.SessionFactoryBuilderImplementor +import org.hibernate.cfg.MappingSettings +import org.hibernate.engine.config.spi.ConfigurationService +import org.hibernate.engine.config.spi.StandardConverters import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment import org.hibernate.engine.spi.FilterDefinition import org.hibernate.generator.GeneratorCreationContext @@ -38,6 +44,7 @@ import org.hibernate.mapping.BasicValue import org.hibernate.mapping.Collection import org.hibernate.mapping.Column import org.hibernate.mapping.Component +import org.hibernate.mapping.GeneratorSettings import org.hibernate.mapping.PersistentClass import org.hibernate.mapping.Property import org.hibernate.mapping.RootClass @@ -203,10 +210,53 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { align(persistentClass, generated, metadata) } } + createIdentifierGenerators(metadata) defineTenantFilter(metadata) return null } + /** + * Hibernate creates the generator of every root's identifier once while it builds the metadata, to let a generator register + * what it exports (the table of a table generator, a sequence), and again when the session factory is built. The generators + * this binder installed are installed only after the metadata is built, so without this call they would register their table + * only when the persisters are built, after Hibernate ordered the columns of every table (by size and name): the table of a + * table generator would then keep the order the generator added its columns in ({@code sequence_name, next_val}) where the + * domain binder's, created in time, is ordered ({@code next_val, sequence_name}). Hibernate itself ignores a + * {@link MappingException} here and raises it again when it builds the session factory, so this does too. + */ + private static void createIdentifierGenerators(MetadataImplementor metadata) { + Database database = metadata.database + ConfigurationService settings = metadata.metadataBuildingOptions.serviceRegistry.requireService(ConfigurationService) + String catalog = settings.getSetting(MappingSettings.DEFAULT_CATALOG, StandardConverters.STRING) + String schema = settings.getSetting(MappingSettings.DEFAULT_SCHEMA, StandardConverters.STRING) + SqlStringGenerationContext context = SqlStringGenerationContextImpl.fromExplicit(database.jdbcEnvironment, database, catalog, schema) + GeneratorSettings generatorSettings = new GeneratorSettings() { + @Override + String getDefaultCatalog() { + return catalog + } + + @Override + String getDefaultSchema() { + return schema + } + + @Override + SqlStringGenerationContext getSqlStringGenerationContext() { + return context + } + } + for (PersistentClass persistentClass : new ArrayList<PersistentClass>(metadata.entityBindings)) { + if (persistentClass instanceof RootClass) { + try { + persistentClass.identifier.createGenerator(database.dialect, (RootClass) persistentClass, persistentClass.identifierProperty, generatorSettings) + } catch (MappingException ignored) { + // raised again, with the same cause, when the session factory is built + } + } + } + } + /** * Hibernate's contributed-class path binds the entity hierarchies only and ignores the global annotations on them, so the * {@code @FilterDef} the generator writes is never read: the filter definition is registered here, as the domain binder diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDdlSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDdlSpec.groovy index 02390b46d1..22344892d9 100644 --- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDdlSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDdlSpec.groovy @@ -34,7 +34,7 @@ import org.hibernate.mapping.RootClass class GeneratedDomainClassesDdlSpec extends HibernateGormDatastoreSpec { void setupSpec() { - registerGeneratedDomainClasses(GddVehicle, GddCar, GddTruck, GddStudent, GddSchool, GddTeacher, GddBadge, GddToken, GddMember, GddAccount) + registerGeneratedDomainClasses(GddVehicle, GddCar, GddTruck, GddStudent, GddSchool, GddTeacher, GddBadge, GddToken, GddMember, GddAccount, GddSequenced) } private List<String> checkClauses(String table) { @@ -145,6 +145,22 @@ class GeneratedDomainClassesDdlSpec extends HibernateGormDatastoreSpec { !uniqueConstraintNames('gdd_account')[0].toUpperCase().startsWith('UK') } + void "the table of a table id generator has its columns in the order Hibernate gives a table it knows when it orders the columns, as with the domain binder"() { + expect: "the generator's own order is sequence_name, next_val; by size the integer comes first" + query("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where upper(TABLE_NAME) = 'GDD_IDS' order by ORDINAL_POSITION")*.toLowerCase() == ['next_val', 'sequence_name'] + } + + void "an entity with a table id generator still gets its ids"() { + when: + GddSequenced first = new GddSequenced(name: 'a').save(flush: true) + GddSequenced second = new GddSequenced(name: 'b').save(flush: true) + + then: + first.id != null + second.id != null + first.id != second.id + } + void "an identifier mapped with type uuid-binary is a binary column, not the database's uuid type, as with the domain binder"() { when: GddToken token = new GddToken(name: 't').save(flush: true) @@ -256,3 +272,11 @@ class GddAccount { id natural: ['zeta', 'alpha'] } } + +@Entity +class GddSequenced { + String name + static mapping = { + id generator: 'table', params: [table_name: 'gdd_ids', segment_value: 'gdd_table'] + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy index 7f68a66914..f2fce5857f 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy @@ -63,7 +63,7 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { * The difference classes kept on purpose, each with the reason it cannot or should not be removed ({@code classify} names them). */ private static final List<Map> KNOWN = [ - [id: 'COLUMN_ORDER', reason: 'The order of the columns inside a table: Hibernate\'s column ordering strategy orders the generated tables by size and name, the binder\'s tables keep the order the binder created them in for the entities of a composite key whose column types the binder swaps (see COMPOSITE_KEY_ORDER) and for the table of a table id generator (next_val, sequence_name). A schema diff tool (Liquibase diff, hibernate validate) does not compare column order, and no a [...] + [id: 'COLUMN_ORDER', reason: 'The order of the columns inside a table of an entity with a composite key whose column types the binder swaps (see COMPOSITE_KEY_ORDER): Hibernate orders the columns by size and name, so the swapped types give the binder another order than the correctly named columns of the generated mode. A schema diff tool (Liquibase diff, hibernate validate) does not compare column order, and matching it would mean mislabelling columns on purpose. Cosmetic. 5 [...] [id: 'COMPOSITE_KEY_ORDER', reason: 'Foreign keys and primary keys over a composite identifier whose parts are mapped in an order other than the sorted one. Hibernate\'s @IdClass key is sorted by property name. (a) Types: the binder names the foreign key columns after the parts in the mapped order but gives them the types of the sorted referenced key, so a part of another type than its neighbour gets the NAME of the other part (child.parent_grand_parent_name is INTEGER, refer [...] [id: 'ENUM_COLUMN_EXTRAS', reason: 'A binder defect (pinned in GrailsDomainBinderOptionDefectSpec): EnumTypeBinder ignores the comment and default expressions of an enum column\'s mapping. The generated mode honours them, so a database created by the binder lacks a default and a comment that the mapping states. Matching the binder would drop what the mapping says; decision for the lead (the 8.x line has the same defect).'], [id: 'IGNORE_NOT_FOUND_FOREIGN_KEY', reason: 'ignoreNotFound: true: Hibernate\'s @NotFound(IGNORE) disables the foreign key (SimpleValue.disableForeignKey, there is no enabling counterpart), the binder keeps it, which makes the option contradict itself (a dangling reference cannot exist). Re-creating the key would need Table.createForeignKey with a name computed through the implicit naming strategy\'s internal ForeignKeyNameSource. Hibernate\'s own behaviour is arguably the r [...]
