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 a6d23902ee1d2b77f3b5e41c3f78c340c52c2151
Author: Walter Duque de Estrada <[email protected]>
AuthorDate: Tue Oct 6 19:42:44 2026 -0500

    fix: give generated composite keys the binder's primary and foreign key 
column order
    
    A composite primary key whose columns a unique group also names takes the 
group's column order in the domain binder (the key is
    created before the primary key, which adopts its order and drops it). 
Hibernate's annotation binder adds the key after the primary
    key and drops it without telling the primary key, so the generator now 
states the order it decided (ConstraintFacets.primaryKeyOrder)
    and the binder sets it as the primary key's ordering unique key.
    
    A to-one foreign key to a composite identifier is created by the domain 
binder with its referenced columns named, in the order of the
    identifier's parts sorted by name. The key Hibernate derives refers to the 
primary key unnamed, and Hibernate puts its columns in the
    order of the primary key (by size and name). The binder now names the 
referenced columns of such a key, so its columns keep the
    sorted order, as the binder's do; the pairs of columns the key relates are 
unchanged.
    
    The DDL differential splits the remaining composite key differences: the 
binder's mislabelled nested foreign key columns and what
    follows from them stay known (COMPOSITE_KEY_TYPE_SWAP, fixed upstream), and 
the duplicate same-named foreign key the binder creates
    for a bidirectional association gets its own known class. Existing 
databases keep the key and column order they were created with.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../cfg/domainbinding/jpa/ConstraintFacets.groovy  |  7 +-
 .../jpa/GeneratedDomainClassBinder.groovy          | 83 ++++++++++++++++++++++
 .../domainbinding/jpa/GrailsDomainGenerator.groovy |  3 +-
 .../generated/GeneratedDomainClassesDdlSpec.groovy | 75 ++++++++++++++++++-
 ...eneratedDomainClassesDdlDifferentialSpec.groovy | 30 +++++---
 .../GrailsDomainGeneratorUniqueGroupSpec.groovy    | 30 +++++++-
 6 files changed, 214 insertions(+), 14 deletions(-)

diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ConstraintFacets.groovy
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ConstraintFacets.groovy
index 91103139a5..bea0593a0f 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ConstraintFacets.groovy
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ConstraintFacets.groovy
@@ -25,6 +25,10 @@ import groovy.transform.CompileStatic
  * names and column order it gives them. {@link GrailsDomainGenerator} writes 
them into
  * {@code @Table(indexes, uniqueConstraints)}.
  *
+ * <p>{@code primaryKeyOrder} is the order of the primary key's columns when a 
unique key over exactly those columns is created
+ * before the primary key, which Hibernate then drops after taking its column 
order for the primary key ({@code null} when there is
+ * no such key).</p>
+ *
  * <p>The indexes come from {@code index:} on a column ({@code IndexBinder}), 
the unique keys from {@code unique:} with
  * a group of properties ({@code CreateKeyForProps}). A plain {@code unique: 
true} is a unique column, not a unique key.</p>
  *
@@ -33,5 +37,6 @@ import groovy.transform.CompileStatic
 @CompileStatic
 record ConstraintFacets(
     List<IndexFacets> indexes,
-    List<UniqueKeyFacets> uniqueKeys) {
+    List<UniqueKeyFacets> uniqueKeys,
+    List<String> primaryKeyOrder) {
 }
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 0198b6cbd3..59f6c5ebfb 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
@@ -44,8 +44,11 @@ import org.hibernate.mapping.BasicValue
 import org.hibernate.mapping.Collection
 import org.hibernate.mapping.Column
 import org.hibernate.mapping.Component
+import org.hibernate.mapping.ForeignKey
 import org.hibernate.mapping.GeneratorSettings
+import org.hibernate.mapping.ManyToOne
 import org.hibernate.mapping.PersistentClass
+import org.hibernate.mapping.PrimaryKey
 import org.hibernate.mapping.Property
 import org.hibernate.mapping.RootClass
 import org.hibernate.mapping.Set as HibernateSet
@@ -210,6 +213,7 @@ class GeneratedDomainClassBinder implements 
SessionFactoryBuilderFactory {
                 align(persistentClass, generated, metadata)
             }
         }
+        alignCompositeForeignKeys(metadata)
         createIdentifierGenerators(metadata)
         defineTenantFilter(metadata)
         return null
@@ -356,6 +360,7 @@ class GeneratedDomainClassBinder implements 
SessionFactoryBuilderFactory {
             key.nameExplicit = false
             key.explicit = false
         }
+        alignPrimaryKeyOrder(persistentClass, entity)
         NaturalIdFacets naturalId = persistentClass instanceof RootClass ? 
generator.naturalIdFacets(entity) : null
         if (naturalId != null) {
             List<String> columns = naturalId.propertyNames().collectMany { 
String name ->
@@ -371,6 +376,84 @@ class GeneratedDomainClassBinder implements 
SessionFactoryBuilderFactory {
         }
     }
 
+    /**
+     * A to-one foreign key to an entity with a composite identifier names the 
referenced columns, in the order of the identifier's
+     * parts sorted by name: the domain binder's {@code 
CompositeIdentifierToManyToOneBinder} creates it with the referenced columns it
+     * collected after {@code Component.sortProperties()}. The key Hibernate 
derives refers to the primary key without naming its
+     * columns, and before the schema is built Hibernate puts the columns of 
such a key in the order it gives the primary key
+     * (by size and name); a key that names its referenced columns keeps the 
order it was created in, which is the sorted order of
+     * the parts, as the binder's does. The columns of the key already pair 
with the columns of the primary key in that order.
+     */
+    private void alignCompositeForeignKeys(MetadataImplementor metadata) {
+        for (PersistentClass persistentClass : new 
ArrayList<PersistentClass>(metadata.entityBindings)) {
+            if (generatedByName.containsKey(persistentClass.entityName)) {
+                List<Value> values = new ArrayList<Value>()
+                collectValues(persistentClass, values)
+                for (Value value : values) {
+                    if (value instanceof ManyToOne) {
+                        alignCompositeForeignKey((ManyToOne) value)
+                    }
+                }
+            }
+        }
+    }
+
+    private static void collectValues(PersistentClass persistentClass, 
List<Value> into) {
+        if (persistentClass instanceof RootClass && persistentClass.identifier 
instanceof Component) {
+            collectValues((Component) persistentClass.identifier, into)
+        }
+        for (Property property : persistentClass.declaredProperties) {
+            into << property.value
+            if (property.value instanceof Component) {
+                collectValues((Component) property.value, into)
+            }
+        }
+    }
+
+    private static void collectValues(Component component, List<Value> into) {
+        for (Property property : component.properties) {
+            into << property.value
+            if (property.value instanceof Component) {
+                collectValues((Component) property.value, into)
+            }
+        }
+    }
+
+    private void alignCompositeForeignKey(ManyToOne value) {
+        Generated target = generatedByName.get(value.referencedEntityName)
+        if (target == null || target.entity().compositeIdentity == null) {
+            return
+        }
+        ForeignKey key = value.table.foreignKeys.values().find { ForeignKey 
candidate ->
+            candidate.referencedEntityName == value.referencedEntityName && 
candidate.columns == value.columns
+        }
+        if (key != null && key.referencedColumns.isEmpty() && 
key.referencedTable.primaryKey != null) {
+            key.addReferencedColumns(new 
ArrayList<Column>(key.referencedTable.primaryKey.columns))
+        }
+    }
+
+    /**
+     * A unique key over exactly the columns of the primary key orders the 
primary key's columns: the domain binder creates the
+     * primary key after the key, and Hibernate takes the order of the key for 
the primary key and drops the key
+     * ({@code Table.setPrimaryKey}). Hibernate's annotation binder adds the 
key after the primary key and drops it without telling
+     * the primary key, so the order the generator decided (the binder's) is 
stated here with a key that is not part of the table.
+     */
+    private void alignPrimaryKeyOrder(PersistentClass persistentClass, 
GrailsHibernatePersistentEntity entity) {
+        PrimaryKey primaryKey = persistentClass.table.primaryKey
+        if (!(persistentClass instanceof RootClass) || primaryKey == null) {
+            return
+        }
+        List<String> order = 
generator.constraintFacets(entity).primaryKeyOrder()
+        if (order == null || order.toSet() != 
primaryKey.columns*.name.toSet()) {
+            return
+        }
+        UniqueKey ordering = new UniqueKey(persistentClass.table)
+        for (String name : order) {
+            ordering.addColumn(primaryKey.columns.find { Column column -> 
column.name == name })
+        }
+        primaryKey.orderingUniqueKey = ordering
+    }
+
     private void alignIdentifier(RootClass root, Generated generated, 
MetadataImplementor metadata) {
         GrailsHibernatePersistentEntity entity = generated.entity()
         if (!(entity.identity instanceof HibernateSimpleIdentityProperty)) {
diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy
index 484769fd42..059df741c9 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy
@@ -750,7 +750,8 @@ class GrailsDomainGenerator {
                 },
                 table.uniqueKeys.values().collect { 
org.hibernate.mapping.UniqueKey key ->
                     new UniqueKeyFacets(key.name, key.columns*.name, 
!unbound.contains(key.name))
-                })
+                },
+                table.primaryKey?.orderingUniqueKey?.columns*.name)
     }
 
     private void applyConstraintSites(org.hibernate.mapping.Table table, 
List<ConstraintSite> sites, Set<String> unbound) {
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 22344892d9..4f35fb6063 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, 
GddSequenced)
+        registerGeneratedDomainClasses(GddVehicle, GddCar, GddTruck, 
GddStudent, GddSchool, GddTeacher, GddBadge, GddToken, GddMember, GddAccount, 
GddPair, GddEdition, GddImprint, GddSequenced)
     }
 
     private List<String> checkClauses(String table) {
@@ -145,6 +145,47 @@ class GeneratedDomainClassesDdlSpec extends 
HibernateGormDatastoreSpec {
         !uniqueConstraintNames('gdd_account')[0].toUpperCase().startsWith('UK')
     }
 
+    private List<String> importedKeys(String table) {
+        Session session = sessionFactory.openSession()
+        try {
+            return session.doReturningWork { Connection connection ->
+                List<String> found = []
+                connection.metaData.getImportedKeys(null, null, 
table.toUpperCase()).withCloseable { rows ->
+                    while (rows.next()) {
+                        found << 
"${rows.getString('FKCOLUMN_NAME')}->${rows.getString('PKCOLUMN_NAME')}".toString().toLowerCase()
+                    }
+                }
+                return found
+            } as List<String>
+        } finally {
+            session.close()
+        }
+    }
+
+    void "the primary key of a composite identifier takes the order of the 
unique group over its columns, as with the domain binder"() {
+        expect: "the group names world first, where Hibernate would order two 
columns of one size by name"
+        query("select k.COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE k 
join INFORMATION_SCHEMA.TABLE_CONSTRAINTS t " +
+                "on k.CONSTRAINT_NAME = t.CONSTRAINT_NAME and 
k.CONSTRAINT_SCHEMA = t.CONSTRAINT_SCHEMA " +
+                "where t.CONSTRAINT_TYPE = 'PRIMARY KEY' and 
upper(t.TABLE_NAME) = 'GDD_PAIR' order by k.ORDINAL_POSITION")*.toLowerCase() 
== ['world', 'hello']
+        uniqueConstraintNames('gdd_pair').isEmpty()
+    }
+
+    void "a foreign key to a composite identifier names the referenced columns 
in the order of the sorted parts, as with the domain binder"() {
+        expect: "the primary key of the edition is ordered by size (number 
first), the foreign key follows the parts by name"
+        importedKeys('gdd_imprint') == ['gdd_edition_isbn->isbn', 
'gdd_edition_number->number']
+    }
+
+    void "a foreign key to a composite identifier still saves and loads"() {
+        when:
+        GddEdition edition = new GddEdition(isbn: 'x', number: 2, label: 
'l').save(flush: true)
+        new GddImprint(edition: edition, code: 'c').save(flush: true)
+        session.clear()
+
+        then:
+        GddImprint.list().size() == 1
+        GddImprint.list()[0].edition.label == 'l'
+    }
+
     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']
@@ -273,6 +314,38 @@ class GddAccount {
     }
 }
 
+@Entity
+class GddPair implements Serializable {
+    Long hello
+    Long world
+    static constraints = {
+        hello unique: 'world'
+    }
+    static mapping = {
+        version false
+        id composite: ['hello', 'world']
+    }
+}
+
+@Entity
+class GddEdition implements Serializable {
+    String isbn
+    Integer number
+    String label
+    static mapping = {
+        id composite: ['isbn', 'number']
+    }
+}
+
+@Entity
+class GddImprint implements Serializable {
+    GddEdition edition
+    String code
+    static mapping = {
+        id composite: ['edition', 'code']
+    }
+}
+
 @Entity
 class GddSequenced {
     String name
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 f2fce5857f..8b463cab25 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,8 +63,8 @@ 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 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: 'BINDER_DUPLICATE_FOREIGN_KEY', reason: 'A binder defect: a 
bidirectional association to an entity with a composite identifier gets two 
foreign keys of the same name over the same columns, one from the to-one side 
(referenced columns stated) and one from the collection key (referenced columns 
left to the primary key), listed in two column orders. Hibernate creates one 
constraint of that name; which of the two it is depends on the order the domain 
classes are bound in. Th [...]
+            [id: 'COMPOSITE_KEY_TYPE_SWAP', reason: 'A binder defect: for a 
foreign key to a composite identifier whose part is itself a to-one to a 
composite identifier, 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, referencing the integer 
luckyNumber). The generated mode names them  [...]
             [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 [...]
             [id: 'INVERSE_JOIN_TABLE_NAME', reason: 'A binder defect (pinned 
in ManyToManyOwnershipDefectSpec): when only the owning side of a many-to-many 
names the join table, the inverse side computes the default name and the binder 
creates a second, unused table for it. The generated mode creates the table the 
owning side names (Hibernate derives the inverse side from mappedBy), so the 
unused table is absent. Nothing reads or writes the binder\'s extra table. 3 
tables in the scanned  [...]
@@ -159,6 +159,9 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
             return 'DISCRIMINATOR_CHECK'
         }
         boolean collection = d.joinTable
+        if (d.duplicateName) {
+            return 'BINDER_DUPLICATE_FOREIGN_KEY'
+        }
         if (kind == 'check constraint') {
             return 'SUBCLASS_NOT_NULL_CHECK'
         }
@@ -174,15 +177,11 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
         if (collection && kind in ['column nullable', 'primary key only in 
generated mode', 'unique key only in binder mode']) {
             return 'COLLECTION_TABLE_KEY'
         }
-        if (kind.startsWith('column order')) {
-            return 'COLUMN_ORDER'
-        }
         if (kind == 'column type' && detail.contains('binder=binary(16)')) {
             return 'UUID_ID_TYPE'
         }
-        if (kind.startsWith('column type') || kind.startsWith('foreign key 
columns') || kind.startsWith('foreign key refCols') ||
-                kind.startsWith('primary key column order')) {
-            return 'COMPOSITE_KEY_ORDER'
+        if (kind == 'column type' && !detail.contains('binder=binary(16)')) {
+            return 'COMPOSITE_KEY_TYPE_SWAP'
         }
         if (kind == 'foreign key only in binder mode') {
             return 'IGNORE_NOT_FOUND_FOREIGN_KEY'
@@ -286,6 +285,8 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
         Map<String, Map> foreignKeys = [:]
         for (ForeignKey key : table.foreignKeys.values()) {
             foreignKeys[key.name] = [
+                    // the domain binder can create two keys of one name over 
the same columns in two orders (see BINDER_DUPLICATE_FOREIGN_KEY)
+                    duplicate: foreignKeys.containsKey(key.name),
                     columns  : key.columns*.name,
                     refTable : key.referencedTable?.name,
                     // a key with no referenced columns references the primary 
key of the table
@@ -347,6 +348,14 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
             found << difference
             return
         }
+        // the tables with a swapped column type: the order of their columns 
and of their primary key follows from the types
+        Closure<Void> reclassify = {
+            Set<String> swapped = found.findAll { Map d -> d.cls == 
'COMPOSITE_KEY_TYPE_SWAP' }*.table.toSet()
+            found.findAll { Map d -> d.kind in ['column order', 'primary key 
column order', 'foreign key columns', 'foreign key refCols'] && 
swapped.contains(d.table) }.each { Map d ->
+                d.cls = 'COMPOSITE_KEY_TYPE_SWAP'
+            }
+            return
+        }
         Set<String> names = (binder.tables.keySet() + 
generated.tables.keySet()) as Set<String>
         for (String name : names.sort()) {
             Map b = binder.tables[name]
@@ -377,6 +386,7 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
                 add('sequence', name, "binder=${binder.sequences[name]} 
generated=${generated.sequences[name]}")
             }
         }
+        reclassify()
         return found
     }
 
@@ -430,9 +440,9 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
         Set<String> onlyGenerated = (g.keySet() - b.keySet()) as Set<String>
         for (String name : (b.keySet() + g.keySet()).toSet().sort()) {
             if (b[name] != null && g[name] != null && b[name] != g[name]) {
-                for (String facet : b[name].keySet()) {
+                for (String facet : b[name].keySet() - 'duplicate') {
                     if (b[name][facet] != g[name][facet]) {
-                        add("${what} ${facet}".toString(), table, "${name}: 
binder=${b[name][facet]} generated=${g[name][facet]}", tags)
+                        add("${what} ${facet}".toString(), table, "${name}: 
binder=${b[name][facet]} generated=${g[name][facet]}", tags + [duplicateName: 
b[name].duplicate == true])
                     }
                 }
             }
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorUniqueGroupSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorUniqueGroupSpec.groovy
index 1ffa1ee94b..2231230110 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorUniqueGroupSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorUniqueGroupSpec.groovy
@@ -35,7 +35,7 @@ import 
org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersi
 class GrailsDomainGeneratorUniqueGroupSpec extends 
GrailsDomainGeneratorSupport {
 
     void setupSpec() {
-        manager.registerDomainClasses(GenUqTarget, GenUqOwner, GenUqChild, 
GenUqJoinedRoot, GenUqJoinedChild, GenUqEnum, GenUqCollection)
+        manager.registerDomainClasses(GenUqTarget, GenUqOwner, GenUqChild, 
GenUqJoinedRoot, GenUqJoinedChild, GenUqEnum, GenUqCollection, GenUqPair)
     }
 
     void "a unique group is a unique constraint on the table over the columns 
of the group"() {
@@ -101,6 +101,21 @@ class GrailsDomainGeneratorUniqueGroupSpec extends 
GrailsDomainGeneratorSupport
         entity(GenUqEnum).persistentClass.table.uniqueKeys.values().every { 
it.columns.size() < 2 }
     }
 
+    void "a unique group over the columns of a composite identifier states the 
order of its primary key, as the binder gives it"() {
+        when:
+        generateGroup(GenUqPair)
+
+        then: "the group names world first, and the key itself is dropped by 
Hibernate, as the primary key's ordering"
+        newGenerator().constraintFacets(entity(GenUqPair)).primaryKeyOrder() 
== ['world', 'hello']
+        
newGenerator().constraintFacets(entity(GenUqPair)).uniqueKeys().isEmpty()
+        
entity(GenUqPair).persistentClass.table.primaryKey.orderingUniqueKey.columns*.name
 == ['world', 'hello']
+    }
+
+    void "an entity without such a group states no order for its primary 
key"() {
+        expect:
+        newGenerator().constraintFacets(entity(GenUqTarget)).primaryKeyOrder() 
== null
+    }
+
     void "a unique group on a collection property is rejected by name, because 
the binder makes it a key of the collection table"() {
         when:
         generateGroup(GenUqCollection)
@@ -243,3 +258,16 @@ class GenUqCollection {
         tags unique: 'x'
     }
 }
+
+@Entity
+class GenUqPair implements Serializable {
+    Long hello
+    Long world
+    static constraints = {
+        hello unique: 'world'
+    }
+    static mapping = {
+        version false
+        id composite: ['hello', 'world']
+    }
+}

Reply via email to