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 24f114b337532bb172691e0cfd8872d2155c482e
Author: Walter Duque de Estrada <[email protected]>
AuthorDate: Wed Oct 7 20:34:17 2026 -0500

    feat: accept an index or a unique group on a collection property in native 
domain binding
    
    The generator refused any mapping with index: or a unique group on a 
hasMany property. The domain
    binder binds the key column of a collection like any other column, so 
index: creates an index of the
    collection table over the key column (and over the element column of a 
collection of enums), with the
    name the mapping gives it. A unique group names columns of the owner's 
table, which the collection
    table does not have, so the key the binder creates cannot be created (fixed 
on the 8.0.x line).
    
    The generator now decides the indexes with the binder's own IndexBinder on 
a scratch table, and the
    aligner creates them on the table Hibernate bound for the collection: the 
inverse side of a
    many-to-many has no table annotation to state them on, and the binder 
indexes the key of both sides
    in the one join table. A unique group on a collection property states no 
key. An index given as a
    closure configures the index column and names no index, since the binder 
would name it after the
    closure instance, a name that differs on every boot. The DDL differential 
knows both as differences
    of the binder, and the 8 fixtures that were refused compile into both 
differentials.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../cfg/domainbinding/jpa/CollectionFacets.groovy  |  10 +-
 .../jpa/GeneratedDomainClassBinder.groovy          |  32 ++
 .../domainbinding/jpa/GrailsDomainGenerator.groovy |  68 ++--
 .../cfg/domainbinding/jpa/ToManyFacets.groovy      |  10 +-
 ...edDomainClassesCollectionConstraintsSpec.groovy | 357 +++++++++++++++++++++
 ...eneratedDomainClassesDdlDifferentialSpec.groovy |  13 +-
 .../GrailsDomainGeneratorDifferentialSpec.groovy   |  32 +-
 .../jpa/GrailsDomainGeneratorIndexSpec.groovy      |  22 +-
 .../GrailsDomainGeneratorOptionCoverageSpec.groovy |  18 +-
 .../GrailsDomainGeneratorUniqueGroupSpec.groovy    |  16 +-
 .../advancedGORMFeatures/nativeDomainBinding.adoc  |  10 +-
 11 files changed, 518 insertions(+), 70 deletions(-)

diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/CollectionFacets.groovy
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/CollectionFacets.groovy
index ebde8f77e4..b9bcbb9bb2 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/CollectionFacets.groovy
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/CollectionFacets.groovy
@@ -41,6 +41,13 @@ import org.hibernate.FetchMode
  * type of that name. It is {@code null} when the mapping states none, or the 
type is the default (an integer for a list, a string for
  * a map). A list's index stays an integer in Java whatever its JDBC type; the 
key of a map is typed with the facets' Java type.</p>
  *
+ * <p>{@code indexes} are the indexes the binder puts on the table of the 
collection when the mapping gives the collection property an
+ * {@code index:}, with the names and the column order it gives them: over the 
key column and, for a collection of enums, the element
+ * column too. It is empty when there are none, or when the binder binds no 
key column for the property (it is mapped by the foreign key of
+ * the other side, or the join table maps its key columns). A {@code unique} 
group on the property creates no key: it names columns of the
+ * owner's table, which the table of the collection does not have. {@link 
GeneratedDomainClassBinder} creates the indexes on the bound
+ * table, since the inverse side of a many-to-many has no table annotation of 
its own to state them on.</p>
+ *
  * <p>{@code extraLazy} is an explicit {@code lazy: true}: the binder makes 
the collection extra-lazy, which Hibernate's annotation
  * binder cannot state, so {@code GeneratedDomainClassBinder} sets it on the 
collection after binding.</p>
  *
@@ -62,5 +69,6 @@ record CollectionFacets(
     String cacheUsage,
     List<ColumnFacets> keys,
     List<String> referencedKeys,
-    TypeFacets indexType) {
+    TypeFacets indexType,
+    List<IndexFacets> indexes) {
 }
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 8a63ef0851..0ccac33665 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
@@ -556,6 +556,7 @@ class GeneratedDomainClassBinder implements 
SessionFactoryBuilderFactory {
             alignExtraLazy((Collection) property.value, 
(HibernatePersistentProperty) persistentProperty)
             alignCollectionTable((Collection) property.value, 
(HibernatePersistentProperty) persistentProperty)
             alignListIndexLength((Collection) property.value, 
(HibernatePersistentProperty) persistentProperty)
+            alignCollectionIndexes((Collection) property.value, 
(HibernatePersistentProperty) persistentProperty)
         }
         if (property.value instanceof Component && persistentProperty 
instanceof Embedded) {
             // PropertyBinder marks the property lazy when the mapping says 
lazy: true; @Basic(fetch = LAZY) on an @Embedded is ignored
@@ -592,6 +593,37 @@ class GeneratedDomainClassBinder implements 
SessionFactoryBuilderFactory {
         }
     }
 
+    /**
+     * The domain binder indexes the key column of a collection (and the 
element column of a collection of enums) when the mapping puts
+     * {@code index:} on the collection property. {@code @CollectionTable} and 
{@code @JoinTable} could state the index of the owning side
+     * only: the inverse side of a many-to-many has no table annotation of its 
own, and the binder indexes the key of both sides in the one
+     * join table. The indexes the generator decided are created here on the 
table Hibernate bound for the collection, with the names the
+     * mapping gives them.
+     */
+    private void alignCollectionIndexes(Collection collection, 
HibernatePersistentProperty property) {
+        List<IndexFacets> indexes
+        if (property instanceof HibernateToManyEntityProperty) {
+            indexes = generator.toManyFacets((HibernateToManyEntityProperty) 
property).indexes()
+        } else if (property instanceof HibernateBasicProperty) {
+            indexes = generator.collectionFacets((HibernateBasicProperty) 
property).indexes()
+        } else {
+            return
+        }
+        Table table = collection.collectionTable
+        if (table == null) {
+            return
+        }
+        for (IndexFacets facets : indexes) {
+            org.hibernate.mapping.Index index = 
table.getOrCreateIndex(facets.name())
+            for (String name : facets.columns()) {
+                Column column = table.columns.find { Column candidate -> 
candidate.name.equalsIgnoreCase(name.replace('`', '')) }
+                if (column != null) {
+                    index.addColumn(column)
+                }
+            }
+        }
+    }
+
     /**
      * Hibernate's annotation binder gives the index column of a list no 
length, which it sizes as a long string when the mapping types
      * the index as a string (a CLOB, which cannot be a key). The domain 
binder's column has the default length of every column it creates.
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 7fa9930039..f095766b4c 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
@@ -1194,10 +1194,6 @@ class GrailsDomainGenerator {
         if (elementType == null || elementType == Object) {
             return 'the element type is not known'
         }
-        String constraintProblem = collectionConstraintProblem(property)
-        if (constraintProblem != null) {
-            return constraintProblem
-        }
         if (mapped.joinTable.keys != null && mapped.joinTable.keys.size() > 1) 
{
             return 'the join table has a composite key'
         }
@@ -1289,29 +1285,43 @@ class GrailsDomainGenerator {
     }
 
     /**
-     * The binder binds the key column of a collection like any other column 
({@code DependentKeyValueBinder} runs
-     * {@code ColumnBinder} on the property), so an {@code index:} or a {@code 
unique:} group on the collection property
-     * becomes an index or a unique key of the collection table over the key 
column, and for a collection of enums the
-     * element column is indexed too. A unique group names columns of the 
owner's table, which the collection table does not
-     * have. That is not what the mapping means, and not something the 
generator states, so it rejects the property.
+     * The binder binds the key column of a collection like any other column 
({@code DependentKeyValueBinder} runs {@code ColumnBinder}
+     * on the collection property), so an {@code index:} on the property 
becomes an index of the collection table over the key column,
+     * named as the mapping says ({@code IndexBinder}), and for a collection 
of enums the element column is indexed too, before the key.
+     * A {@code unique} group on the property would name columns of the 
owner's table, which the collection table does not have: the
+     * binder creates a key over columns that do not exist (a defect fixed on 
the 8.0.x line), so the generator states none.
+     *
+     * <p>The {@code index:} of a closure is not an index: it configures the 
index column of a list or a map, and the name the binder
+     * gives the index is the closure's own ({@code toString()}, which holds 
the identity of the closure instance and differs on every
+     * boot), so none is stated for it.</p>
      *
-     * @return why the generator rejects the constraint on the collection 
property, or {@code null} when there is none the binder binds
+     * @return the indexes of the collection table in the order the binder 
creates them
      */
-    private static String collectionConstraintProblem(HibernateToManyProperty 
property) {
-        PropertyConfig mapped = property.hibernateMappedForm
-        ColumnConfig columnConfig = firstColumnConfig(mapped)
-        boolean indexed = columnConfig?.index != null && 
!Boolean.FALSE.equals(columnConfig.index) &&
-                !'false'.equalsIgnoreCase(columnConfig.index.toString())
-        boolean bindsKey = property.isBidirectional() ?
-                (property.hibernateInverseSide instanceof 
HibernateManyToManyProperty || Map.isAssignableFrom(property.type)) :
-                !mapped.hasJoinKeyMapping()
-        boolean bindsEnumElement = property instanceof HibernateEnumProperty
-        if ((bindsKey || bindsEnumElement) && indexed || bindsKey && 
mapped.isUniqueWithinGroup()) {
-            return 'an index or a unique group is mapped on the collection 
property: the binder creates it over the key column of the ' +
-                    'collection table (a unique group over columns of the 
owner\'s table, which the collection table does not have), ' +
-                    'which the generator does not state'
+    private List<IndexFacets> collectionTableIndexes(
+            HibernateToManyProperty property, String tableName, 
List<ColumnFacets> keys, ColumnFacets element) {
+        ColumnConfig columnConfig = 
firstColumnConfig(property.hibernateMappedForm)
+        if (tableName == null || columnConfig?.index == null || 
columnConfig.index instanceof Closure) {
+            return []
         }
-        return null
+        org.hibernate.mapping.Table table = new 
org.hibernate.mapping.Table('grails', tableName.replace('`', ''))
+        if (property instanceof HibernateEnumProperty) {
+            indexBinder.bindIndex(element.name(), new Column(element.name()), 
columnConfig, table)
+        }
+        if (bindsCollectionKey(property)) {
+            GrailsHibernatePersistentEntity owner = property.hibernateOwner
+            List<ColumnConfig> configs = compositeIdentifier(owner) ? 
compositeForeignKeyConfigs(property, owner) : [columnConfig]
+            for (int i = 0; i < keys.size() && i < configs.size(); i++) {
+                indexBinder.bindIndex(keys[i].name(), new 
Column(keys[i].name()), configs[i], table)
+            }
+        }
+        return table.indexes.values().collect { org.hibernate.mapping.Index 
index -> new IndexFacets(index.name, index.columns*.name) }
+    }
+
+    /** Whether the binder binds the key column of the collection like a 
column of the mapping (and so indexes it). */
+    private static boolean bindsCollectionKey(HibernateToManyProperty 
property) {
+        return property.isBidirectional() ?
+                (property.hibernateInverseSide instanceof 
HibernateManyToManyProperty || Map.isAssignableFrom(property.type)) :
+                !property.hibernateMappedForm.hasJoinKeyMapping()
     }
 
     /**
@@ -1345,7 +1355,8 @@ class GrailsDomainGenerator {
                 property.cacheUsage,
                 collectionKeyColumns(property),
                 collectionKeyReferencedColumns(property),
-                collectionIndexType(property, kind))
+                collectionIndexType(property, kind),
+                collectionTableIndexes(property, 
tableForMany.getTableName(property), collectionKeyColumns(property), 
collectionElementFacets(property, kind)))
     }
 
     /**
@@ -1572,10 +1583,6 @@ class GrailsDomainGenerator {
         if (mapped.type != null) {
             return 'a type is mapped on the collection property itself, which 
the binder applies to the collection and its element alike'
         }
-        String constraintProblem = collectionConstraintProblem(property)
-        if (constraintProblem != null) {
-            return constraintProblem
-        }
         if (property instanceof HibernateManyToManyProperty) {
             HibernateAssociation other = property.hibernateInverseSide
             if (!(other instanceof HibernateManyToManyProperty) || 
Map.isAssignableFrom(other.type)) {
@@ -1732,7 +1739,8 @@ class GrailsDomainGenerator {
                 condition,
                 keys != null ? keys : [key],
                 keys != null ? collectionKeyReferencedColumns(property) : [],
-                collectionIndexType(property, kind))
+                collectionIndexType(property, kind),
+                collectionTableIndexes(property, table, keys != null ? keys : 
[key], element))
     }
 
     /**
diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ToManyFacets.groovy
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ToManyFacets.groovy
index 0b5bd9502a..a4a8b5fc62 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ToManyFacets.groovy
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ToManyFacets.groovy
@@ -49,6 +49,13 @@ import org.hibernate.FetchMode
  * type of that name. It is {@code null} when the mapping states none, or the 
type is the default (an integer for a list, a string for
  * a map). A list's index stays an integer in Java whatever its JDBC type; the 
key of a map is typed with the facets' Java type.</p>
  *
+ * <p>{@code indexes} are the indexes the binder puts on the table of the 
collection when the mapping gives the collection property an
+ * {@code index:}, with the names and the column order it gives them: over the 
key column and, for a collection of enums, the element
+ * column too. It is empty when there are none, or when the binder binds no 
key column for the property (it is mapped by the foreign key of
+ * the other side, or the join table maps its key columns). A {@code unique} 
group on the property creates no key: it names columns of the
+ * owner's table, which the table of the collection does not have. {@link 
GeneratedDomainClassBinder} creates the indexes on the bound
+ * table, since the inverse side of a many-to-many has no table annotation of 
its own to state them on.</p>
+ *
  * <p>{@code extraLazy} is an explicit {@code lazy: true}: the binder makes 
the collection extra-lazy, which Hibernate's annotation
  * binder cannot state, so {@code GeneratedDomainClassBinder} sets it on the 
collection after binding.</p>
  *
@@ -77,5 +84,6 @@ record ToManyFacets(
     String tenantCondition,
     List<ColumnFacets> keys,
     List<String> referencedKeys,
-    TypeFacets indexType) {
+    TypeFacets indexType,
+    List<IndexFacets> indexes) {
 }
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionConstraintsSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionConstraintsSpec.groovy
new file mode 100644
index 0000000000..49021a5ba5
--- /dev/null
+++ 
b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionConstraintsSpec.groovy
@@ -0,0 +1,357 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package grails.gorm.tests.generated
+
+import java.util.concurrent.atomic.AtomicInteger
+
+import grails.gorm.annotation.Entity
+import org.hibernate.mapping.Table
+import spock.lang.AutoCleanup
+import spock.lang.Specification
+import spock.lang.Unroll
+
+import org.grails.orm.hibernate.HibernateDatastore
+
+/**
+ * An {@code index:} or a {@code unique:} group mapped on a collection 
property, booted through the generated classes and through
+ * the domain binder. The binder binds the key column of a collection like any 
other column, so {@code index:} creates an index
+ * over the key column of the collection table (and, for a collection of 
enums, over the element column too), named as the mapping
+ * says; a unique group names columns of the owner's table, which the 
collection table does not have, so it creates no key in the
+ * generated mode (the binder's impossible key is a defect fixed on the 8.0.x 
line).
+ */
+class GeneratedDomainClassesCollectionConstraintsSpec extends Specification {
+
+    static final AtomicInteger BOOTS = new AtomicInteger()
+
+    @AutoCleanup
+    HibernateDatastore datastore
+
+    private HibernateDatastore boot(List<Class> group, boolean generated) {
+        datastore?.close()
+        datastore = new HibernateDatastore([
+                'dataSource.url'                  : 
"jdbc:h2:mem:ccs${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+                'dataSource.dbCreate'             : 'create-drop',
+                'hibernate.generatedDomainClasses': generated,
+        ], group as Class[])
+        return datastore
+    }
+
+    /** The tables of the boot model as plain data: the columns with their 
type, the indexes and the unique keys. */
+    private Map<String, Map> schema(List<Class> group, boolean generated) {
+        HibernateDatastore booted = boot(group, generated)
+        Map<String, Map> result = new TreeMap<String, Map>()
+        for (Table table : booted.metadata.collectTableMappings()) {
+            if (table.physicalTable) {
+                result[table.name] = [
+                        columns   : table.columns.collectEntries { 
org.hibernate.mapping.Column column ->
+                            // a primary key column is not null in the schema 
whatever the column says
+                            boolean nullable = column.nullable && 
!(table.primaryKey != null && 
table.primaryKey.columns*.name.contains(column.name))
+                            [(column.name): 
"${column.getSqlType(booted.metadata)}${nullable ? '' : ' not 
null'}".toString()]
+                        },
+                        primaryKey: table.primaryKey?.columns*.name?.sort(),
+                        indexes   : table.indexes.values().collectEntries { 
[(it.name): it.columns*.name] },
+                        uniqueKeys: table.uniqueKeys.values().collect { 
it.columns*.name.sort() }.sort { it.toString() },
+                ]
+            }
+        }
+        return result
+    }
+
+    /** The names of the indexes H2 itself holds on a table, whatever it 
generated for keys. */
+    private List<String> h2Indexes(String table) {
+        List<String> found = []
+        
datastore.connectionSources.defaultConnectionSource.dataSource.connection.withCloseable
 { java.sql.Connection connection ->
+            connection.createStatement().withCloseable { java.sql.Statement 
statement ->
+                statement.executeQuery(
+                        "select INDEX_NAME from INFORMATION_SCHEMA.INDEXES 
where upper(TABLE_NAME) = '${table.toUpperCase()}' " +
+                                "and INDEX_TYPE_NAME = 'INDEX' order by 
INDEX_NAME".toString()).withCloseable { java.sql.ResultSet rows ->
+                    while (rows.next()) {
+                        found << rows.getString(1).toLowerCase()
+                    }
+                }
+            }
+        }
+        return found.findAll { String name -> !name.startsWith('fk') }
+    }
+
+    @Unroll
+    void "an index mapped on #label creates the indexes the domain binder 
creates"() {
+        when:
+        Map<String, Map> binder = schema(group, false)
+        Map<String, Map> generated = schema(group, true)
+
+        then: "the indexes and keys of every table are the binder's (the 
binder leaves an unused column in the table of a map of values)"
+        generated.keySet() == binder.keySet()
+        generated.collectEntries { String name, Map description -> [(name): 
[description.indexes, description.uniqueKeys]] } ==
+                binder.collectEntries { String name, Map description -> 
[(name): [description.indexes, description.uniqueKeys]] }
+        generated[table].indexes == indexes
+
+        where:
+        label                                    | group                | 
table                  | indexes
+        'a set of strings'                       | [CcsSetIdx]          | 
'ccs_set_idx_tags'     | [ccs_tags_idx: ['ccs_set_idx_id']]
+        'a set, with true'                       | [CcsIndexTrue]       | 
'ccs_index_true_tags'  | [ccs_index_true_tags_ccs_index_true_id_idx: 
['ccs_index_true_id']]
+        'a set, with two names'                  | [CcsIndexMulti]      | 
'ccs_index_multi_tags' | [ccs_a: ['ccs_index_multi_id'], ccs_b: 
['ccs_index_multi_id']]
+        'a set, with false'                      | [CcsIndexFalse]      | 
'ccs_index_false_tags' | [:]
+        'a set of enums, over the element too'   | [CcsEnumIdx]         | 
'ccs_enum_idx_colors'  | [ccs_color_idx: ['ccs_color', 'ccs_enum_idx_id']]
+        'a list, which names its index column'   | [CcsListIdx]         | 
'ccs_list_idx_items'   | [ccs_items_idx: ['ccs_list_idx_id']]
+        'a map'                                  | [CcsMapIdx]          | 
'ccs_map_idx_attrs'    | [ccs_attrs_idx: ['ccs_map_idx_id']]
+        'a map, with the settings of the index column' | [CcsMapSettings] | 
'ccs_map_settings_attrs' | ['[column:ccs_k': ['ccs_map_settings_id'], 
'type:string]': ['ccs_map_settings_id']]
+        'a list of long, with the settings of the index column' | 
[CcsListSettings] | 'ccs_list_settings_items' | ['[column:ccs_ix': 
['ccs_list_settings_id'], 'type:long]': ['ccs_list_settings_id']]
+        'a one-to-many through a join table'     | [CcsKidOwner, CcsKid] | 
'ccs_kid_owner_ccs_kid' | [ccs_kids_idx: ['ccs_kid_owner_kids_id']]
+        'a many-to-many, on both sides'          | [CcsLeft, CcsRight]  | 
'ccs_left_rights'      | [ccs_right_idx: ['ccs_right_id'], ccs_left_idx: 
['ccs_left_id']]
+        'a collection with a mapped join key'    | [CcsJoinKey]         | 
'ccs_tags_table'       | [:]
+        'a one-to-many mapped by a foreign key'  | [CcsParent, CcsChild] | 
'ccs_child'           | [:]
+    }
+
+    void "the indexes are created in the database, over the key column of the 
collection table"() {
+        when:
+        boot([CcsSetIdx, CcsEnumIdx], true)
+
+        then:
+        h2Indexes('ccs_set_idx_tags') == ['ccs_tags_idx']
+        h2Indexes('ccs_enum_idx_colors') == ['ccs_color_idx']
+    }
+
+    void "a closure mapped as the index names no index, as its name would be 
the closure's own, which differs on every boot"() {
+        when:
+        Map<String, Map> binder = schema([CcsClosureIdx], false)
+        Map<String, Map> generated = schema([CcsClosureIdx], true)
+
+        then: "both name the index column after the closure, and only the 
binder creates an index, named after the closure instance"
+        generated['ccs_closure_idx_items'].columns == 
binder['ccs_closure_idx_items'].columns
+        generated['ccs_closure_idx_items'].columns.keySet().contains('ccs_cx')
+        generated['ccs_closure_idx_items'].indexes.isEmpty()
+        binder['ccs_closure_idx_items'].indexes.size() == 1
+        
binder['ccs_closure_idx_items'].indexes.keySet().first().contains('closure')
+    }
+
+    @Unroll
+    void "a unique group mapped on #label creates no key, since the collection 
table does not hold the columns of the group"() {
+        when:
+        Map<String, Map> generated = schema(group, true)
+
+        then: "the owner's table has no key either, and the table of the 
collection holds the keys of the set only"
+        generated[owner].uniqueKeys.isEmpty()
+        generated[table].uniqueKeys.every { List<String> columns -> 
columns.every { String column -> column in generated[table].columns.keySet() } }
+        !generated[table].uniqueKeys.any { List<String> columns -> 'x' in 
columns }
+
+        where:
+        label                    | group           | owner           | table
+        'a set of strings'       | [CcsUqGroup]    | 'ccs_uq_group'  | 
'ccs_uq_group_tags'
+        'a list'                 | [CcsUqList]     | 'ccs_uq_list'   | 
'ccs_uq_list_items'
+        'a set of enums'         | [CcsUqEnum]     | 'ccs_uq_enum'   | 
'ccs_uq_enum_colors'
+    }
+
+    void "a collection with a unique group and an index saves and loads, and 
the group does not reject a repeated value"() {
+        given:
+        boot([CcsUqGroup, CcsSetIdx], true)
+
+        when:
+        Long id = CcsUqGroup.withTransaction {
+            new CcsUqGroup(x: 'a', tags: ['one', 'two'] as 
Set).save(failOnError: true, flush: true).id
+        }
+        CcsUqGroup.withTransaction {
+            new CcsUqGroup(x: 'a', tags: ['one'] as Set).save(failOnError: 
true, flush: true)
+        }
+        Long indexed = CcsSetIdx.withTransaction {
+            new CcsSetIdx(tags: ['x', 'y', 'z'] as Set).save(failOnError: 
true, flush: true).id
+        }
+
+        then:
+        CcsUqGroup.withNewSession { CcsUqGroup.get(id).tags } == ['one', 
'two'] as Set
+        CcsUqGroup.withNewSession { CcsUqGroup.count() } == 2
+        CcsSetIdx.withNewSession { CcsSetIdx.get(indexed).tags } == ['x', 'y', 
'z'] as Set
+    }
+
+    void "a list, a map and a one-to-many with an index save, reload and are 
found through queries"() {
+        given:
+        boot([CcsListIdx, CcsMapIdx, CcsKidOwner, CcsKid, CcsLeft, CcsRight], 
true)
+
+        when:
+        Long listId = CcsListIdx.withTransaction { new CcsListIdx(items: ['a', 
'b', 'c']).save(failOnError: true, flush: true).id }
+        Long mapId = CcsMapIdx.withTransaction { new CcsMapIdx(attrs: [k1: 
'v1', k2: 'v2']).save(failOnError: true, flush: true).id }
+        Long ownerId = CcsKidOwner.withTransaction {
+            CcsKidOwner owner = new CcsKidOwner()
+            owner.addToKids(new CcsKid(name: 'kid'))
+            owner.save(failOnError: true, flush: true).id
+        }
+        Long leftId = CcsLeft.withTransaction {
+            CcsLeft left = new CcsLeft()
+            left.addToRights(new CcsRight())
+            left.save(failOnError: true, flush: true).id
+        }
+
+        then:
+        CcsListIdx.withNewSession { CcsListIdx.get(listId).items } == ['a', 
'b', 'c']
+        CcsMapIdx.withNewSession { CcsMapIdx.get(mapId).attrs } == [k1: 'v1', 
k2: 'v2']
+        CcsKidOwner.withNewSession { CcsKidOwner.get(ownerId).kids*.name } == 
['kid']
+        CcsLeft.withNewSession { CcsLeft.get(leftId).rights.size() } == 1
+        CcsRight.withNewSession { CcsRight.list().first().lefts.size() } == 1
+        CcsListIdx.withNewSession { CcsListIdx.where { items.size() == 3 
}.count() } == 1
+    }
+}
+
+enum CcsColor { RED, GREEN }
+
+@Entity
+class CcsSetIdx {
+    Set<String> tags
+    static hasMany = [tags: String]
+    static mapping = { tags index: 'ccs_tags_idx' }
+}
+
+@Entity
+class CcsIndexTrue {
+    Set<String> tags
+    static hasMany = [tags: String]
+    static mapping = { tags index: true }
+}
+
+@Entity
+class CcsIndexMulti {
+    Set<String> tags
+    static hasMany = [tags: String]
+    static mapping = { tags index: 'ccs_a, ccs_b' }
+}
+
+@Entity
+class CcsIndexFalse {
+    Set<String> tags
+    static hasMany = [tags: String]
+    static mapping = { tags index: false }
+}
+
+@Entity
+class CcsEnumIdx {
+    Set<CcsColor> colors
+    static hasMany = [colors: CcsColor]
+    static mapping = { colors index: 'ccs_color_idx' }
+}
+
+@Entity
+class CcsListIdx {
+    List<String> items
+    static hasMany = [items: String]
+    static mapping = { items index: 'ccs_items_idx' }
+}
+
+@Entity
+class CcsMapIdx {
+    Map<String, String> attrs
+    static hasMany = [attrs: String]
+    static mapping = { attrs index: 'ccs_attrs_idx' }
+}
+
+@Entity
+class CcsMapSettings {
+    Map<String, String> attrs
+    static hasMany = [attrs: String]
+    static mapping = { attrs index: [column: 'ccs_k', type: 'string'] }
+}
+
+@Entity
+class CcsListSettings {
+    List<String> items
+    static hasMany = [items: String]
+    static mapping = { items index: [column: 'ccs_ix', type: 'long'] }
+}
+
+@Entity
+class CcsClosureIdx {
+    List<String> items
+    static hasMany = [items: String]
+    static mapping = {
+        items index: {
+            column name: 'ccs_cx'
+        }
+    }
+}
+
+@Entity
+class CcsKid {
+    String name
+}
+
+@Entity
+class CcsKidOwner {
+    Set<CcsKid> kids
+    static hasMany = [kids: CcsKid]
+    static mapping = { kids index: 'ccs_kids_idx' }
+}
+
+@Entity
+class CcsLeft {
+    Set<CcsRight> rights
+    static hasMany = [rights: CcsRight]
+    static mapping = { rights index: 'ccs_left_idx' }
+}
+
+@Entity
+class CcsRight {
+    Set<CcsLeft> lefts
+    static hasMany = [lefts: CcsLeft]
+    static belongsTo = [CcsLeft]
+    static mapping = { lefts index: 'ccs_right_idx' }
+}
+
+@Entity
+class CcsJoinKey {
+    Set<String> tags
+    static hasMany = [tags: String]
+    static mapping = {
+        tags joinTable: [name: 'ccs_tags_table', key: 'owner_fk', column: 
'tag_value'], index: 'ccs_jk_idx'
+    }
+}
+
+@Entity
+class CcsParent {
+    Set<CcsChild> children
+    static hasMany = [children: CcsChild]
+    static mapping = { children index: 'ccs_children_idx' }
+}
+
+@Entity
+class CcsChild {
+    CcsParent parent
+    static belongsTo = [parent: CcsParent]
+}
+
+@Entity
+class CcsUqGroup {
+    String x
+    Set<String> tags
+    static hasMany = [tags: String]
+    static mapping = { tags unique: 'x' }
+}
+
+@Entity
+class CcsUqList {
+    String x
+    List<String> items
+    static hasMany = [items: String]
+    static mapping = { items unique: 'x' }
+}
+
+@Entity
+class CcsUqEnum {
+    String x
+    Set<CcsColor> colors
+    static hasMany = [colors: CcsColor]
+    static mapping = { colors unique: 'x' }
+}
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 c91853f0cc..efc61e1de2 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
@@ -64,12 +64,14 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
      */
     private static final List<Map> KNOWN = [
             [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: 'CLOSURE_INDEX_NAME', reason: 'A closure mapped as the index 
of a collection property (index: { column name: ... }, which configures the 
index column of a list or a map): the binder also reads it as the name of an 
index of the collection table and names it with the closure\'s toString(), 
which holds the identity of the closure instance (...$_closure2@3ff5aef4) and 
differs on every boot. A name that cannot be reproduced is not stated: the 
generated mode creates the index  [...]
             [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: '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 mapping that names the 
join table on both sides of a many-to-many with different names (the binder 
adopts the owning side\'s name only when the inverse side names none, since the 
8.0.x fix for the inverse join table): the inverse side keeps its own 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 tabl [...]
             [id: 'LIST_INDEX_CHECK', reason: 'Hibernate adds check (<index 
column> >= 0) to the index column of every list 
(IndexColumn.addIndexCheckConstraint, always, for @OrderColumn) and offers no 
annotation to avoid it; Column.getCheckConstraints() is unmodifiable and Column 
has no removal method (Column.copy shares the list), so it cannot be removed 
through public API, only by reflection on the private list, which is not done. 
The check can never reject a value GORM writes (indexes [...]
             [id: 'MAP_ELEMENT_NULLABLE', reason: 'The mapping of a map of 
values states nullable: false on the element column and the binder leaves the 
column nullable (it ignores the option, like the enum column extras); the 
generated mode honours the mapping, so a database created by the binder has a 
nullable column where the generated mode creates NOT NULL. Matching the binder 
would drop a constraint the mapping states.'],
             [id: 'MAP_UNUSED_COLUMN', reason: 'The binder leaves an unused 
nullable column in the table of a map of values (the element it bound before 
the map replaced it, attributes_java_lang_string); the generated mode creates 
no such column. Nothing reads the extra column; an existing database keeps it 
(update does not drop columns).'],
+            [id: 'UNIQUE_GROUP_ON_COLLECTION', reason: 'A binder defect (fixed 
on the 8.0.x line by PR 16533, so the class disappears with the next up-merge): 
a unique group mapped on a collection property makes the binder create a unique 
key on the collection table over the key column and the other properties of the 
group, which are columns of the owner\'s table and not of the collection table, 
so the key cannot be created (Hibernate logs the failed statement and boots; 
the key is not i [...]
             [id: 'UNIQUE_GROUP_ON_ENUM', reason: 'A binder defect (pinned in 
GrailsDomainBinderOptionDefectSpec): a unique group that includes an enum 
property is dropped by the binder. The generated mode creates the constraint 
the mapping states, so a database created by the binder lacks it and `update` 
would add it. 2 groups in the scanned domains.']
     ]
 
@@ -82,7 +84,6 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
             'is registered for the Java type',
             'names a class that is not a UserType',
             'a type is mapped on the collection property itself',
-            'an index or a unique group is mapped on the collection property',
             'is a collection inside an embedded type',
             'declares a natural id but is a subclass',
             'which is HibernateEmbeddedProperty',
@@ -173,6 +174,12 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
         if (collection && kind == 'column nullable' && 
d.collections*.startsWith('Map of BasicValue').any()) {
             return 'MAP_ELEMENT_NULLABLE'
         }
+        if (collection && kind == 'index only in binder mode' && (detail =~ 
/_closure\d+@[0-9a-f]+/).find()) {
+            return 'CLOSURE_INDEX_NAME'
+        }
+        if (kind == 'unique key only in binder mode' && d.impossibleKey) {
+            return 'UNIQUE_GROUP_ON_COLLECTION'
+        }
         if (collection && kind in ['column nullable', 'primary key only in 
generated mode', 'unique key only in binder mode']) {
             return 'COLLECTION_TABLE_KEY'
         }
@@ -371,7 +378,9 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
             compareColumns(name, b, g, add, tags)
             comparePrimaryKeys(name, b, g, add, tags)
             compareNamed('foreign key', name, b.foreignKeys, g.foreignKeys, 
['columns', 'refTable'], add, tags)
-            compareNamed('unique key', name, b.uniqueKeys, g.uniqueKeys, 
['columns'], add, tags)
+            // a key over a column the table does not have cannot be created: 
the group names columns of the owner's table
+            Map keyTags = tags + [impossibleKey: tags.joinTable && 
b.uniqueKeys.values().any { Map key -> key.columns.any { String column -> 
!b.columns.containsKey(column) } }]
+            compareNamed('unique key', name, b.uniqueKeys, g.uniqueKeys, 
['columns'], add, keyTags)
             compareNamed('index', name, b.indexes, g.indexes, ['columns'], 
add, tags)
             if (b.checks != g.checks) {
                 add('check constraint', name, "binder=${b.checks} 
generated=${g.checks}", tags)
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy
index e036390f7f..5960b29c46 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy
@@ -839,20 +839,33 @@ class GrailsDomainGeneratorDifferentialSpec extends 
HibernateGormDatastoreSpec {
                 found << "${where} tableColumns: generator=${described} 
binder=${collection.collectionTable.columns*.name}".toString()
             }
         }
-        found.addAll(compareCollectionTableIndexes(where, collection))
+        found.addAll(compareCollectionTableIndexes(where, facets.indexes(), 
collection, false, known))
         return found
     }
 
     /**
-     * The generator states no index on the table of a collection: the binder 
only creates one there when the mapping puts
-     * {@code index:} on the collection property, which the generator rejects, 
so any index it finds is a mapping the generator
-     * accepted and drops.
+     * The indexes the binder put on the table of a collection against the 
ones the generator decided: the same names over the same
+     * columns in the same order. The two sides of a bidirectional 
many-to-many share the one join table, so each side's indexes are
+     * part of the binder's, which holds both sides'. An index the binder 
named after a closure (the closure's own {@code toString()}, which
+     * holds the identity of the closure instance) is the binder's alone: the 
generator states none for a closure.
      */
-    private static List<String> compareCollectionTableIndexes(String where, 
HibernateCollection collection) {
-        List<String> indexes = 
collection.collectionTable.indexes.values().collect { 
org.hibernate.mapping.Index index ->
-            "${index.name}:${index.columns*.name}".toString()
+    private static List<String> compareCollectionTableIndexes(
+            String where, List<IndexFacets> facets, HibernateCollection 
collection, boolean sharedTable, Map<String, Integer> known) {
+        Map<String, List<String>> bound = [:]
+        for (org.hibernate.mapping.Index index : 
collection.collectionTable.indexes.values()) {
+            if ((index.name =~ /_closure\d+@[0-9a-f]+/).find()) {
+                known['the binder names an index of the collection table after 
the closure mapped as its index, which differs on every boot']++
+            } else {
+                bound[index.name] = index.columns*.name
+            }
+        }
+        Map<String, List<String>> expected = facets.collectEntries { 
IndexFacets index -> [(index.name()): index.columns().collect { it.replace('`', 
'') }] }
+        if (sharedTable) {
+            return expected.findAll { String name, List<String> columns -> 
!bound.containsKey(name) || !bound[name].containsAll(columns) }.collect {
+                String name, List<String> columns -> "${where} 
collectionTableIndexes: generator=${name}:${columns} binder=${bound}".toString()
+            }
         }
-        return indexes.isEmpty() ? [] : ["${where} collectionTableIndexes: 
generator=[] binder=${indexes}".toString()]
+        return expected == bound ? [] : ["${where} collectionTableIndexes: 
generator=${expected} binder=${bound}".toString()]
     }
 
     /** The key of a collection of basic values must be updatable: Hibernate 
writes no rows for a collection whose key is not. */
@@ -1659,7 +1672,8 @@ class GrailsDomainGeneratorDifferentialSpec extends 
HibernateGormDatastoreSpec {
             })
             // Hibernate copies the size of the referenced identifier onto the 
element column after binding
             found.addAll(compareValueColumn("${where} element".toString(), 
facets.element(), collection.element, collection.collectionTable, true))
-            found.addAll(compareCollectionTableIndexes(where, collection))
+            found.addAll(compareCollectionTableIndexes(
+                    where, facets.indexes(), collection, property instanceof 
HibernateManyToManyProperty && property.bidirectional, known))
         }
         found.addAll(circularKeyOrFound(property, 
compareValueColumns("${where} key".toString(), facets.keys(), collection.key, 
collection.collectionTable, true), known))
         if (!((DependantValue) collection.key).updateable) {
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorIndexSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorIndexSpec.groovy
index 1002af30a9..23bb5a2e43 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorIndexSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorIndexSpec.groovy
@@ -24,6 +24,7 @@ import org.hibernate.boot.Metadata
 import org.hibernate.mapping.PersistentClass
 
 import 
org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
+import 
org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty
 
 /**
  * Describes how {@link GrailsDomainGenerator} states the indexes a mapping 
asks for with {@code index:} on a column. The
@@ -115,20 +116,21 @@ class GrailsDomainGeneratorIndexSpec extends 
GrailsDomainGeneratorSupport {
         
readIndexes(metadata.getEntityBinding(classes[entity(GenIdxJoinedChild)].name)) 
== boundIndexes(GenIdxJoinedChild)
     }
 
-    void "an index on a collection property is rejected by name, because the 
binder indexes the key column of the collection table"() {
+    void "an index on a collection property is stated over the key column of 
the collection table, with the name the binder gives it"() {
         when:
-        generateGroup(GenIdxCollections)
+        CollectionFacets facets = 
newGenerator().collectionFacets((HibernateBasicProperty) 
entity(GenIdxCollections).getPropertyByName(property))
+        Map<GrailsHibernatePersistentEntity, Class<?>> classes = 
generateGroup(GenIdxCollections)
 
-        then:
-        UnsupportedOperationException e = thrown()
-        e.message.contains('GenIdxCollections')
-        e.message.contains(property)
-        e.message.contains('index or a unique group')
-        
entity(GenIdxCollections).persistentClass.getProperty(property).value.collectionTable.indexes.values()*.name
 == [indexName]
+        then: "it is created on the bound table after Hibernate binds the 
collection, not by an annotation of the carrier"
+        facets.indexes() == expected.collect { String name, List<String> 
columns -> new IndexFacets(name, columns) }
+        
entity(GenIdxCollections).persistentClass.getProperty(property).value.collectionTable.indexes.values().collect
 {
+            [it.name, it.columns*.name]
+        } == expected.collect { String name, List<String> columns -> [name, 
columns] }
+        
classes[entity(GenIdxCollections)].getAnnotation(Table).indexes().length == 0
 
         where:
-        property | indexName
-        'tags'   | 'gen_idx_tags'
+        property | expected
+        'tags'   | ['gen_idx_tags': ['gen_idx_collections_id']]
     }
 
     private Map<String, List<String>> boundIndexes(Class<?> domain) {
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorOptionCoverageSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorOptionCoverageSpec.groovy
index c1e5f42ab6..41f088f26f 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorOptionCoverageSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorOptionCoverageSpec.groovy
@@ -79,7 +79,9 @@ class GrailsDomainGeneratorOptionCoverageSpec extends 
GrailsDomainGeneratorSuppo
             'property.min'                 : ['number'],
             'property.scale'               : ['number'],
             'property.unique'              : ['basic', 'number', 'target', 
'tags', 'modes', 'targets', 'ordered'],
-            'property.uniqueGroup'         : ['basic', 'number', 'mode', 
'target', 'tags', 'modes', 'targets', 'ordered'],
+            // a unique group on a collection property names columns of the 
owner's table, which the collection table does not have: the binder's
+            // key over them cannot be created (a defect fixed on the 8.0.x 
line), so the generator deliberately states none
+            'property.uniqueGroup'         : ['basic', 'number', 'mode', 
'target'],
             'property.insertable'          : KINDS,
             'property.updatable'           : KINDS,
             'property.type'                : ['basic'],
@@ -405,8 +407,8 @@ class GrailsDomainGeneratorOptionCoverageSpec extends 
GrailsDomainGeneratorSuppo
 
     /**
      * What the generator decides for the group: the generated classes 
(annotations and fields) and the facets that no annotation
-     * carries but the binding of the generated classes applies to the bound 
properties: an extra-lazy collection and a lazy
-     * embedded property.
+     * carries but the binding of the generated classes applies to the bound 
properties: an extra-lazy collection, the indexes of the
+     * table of a collection and a lazy embedded property.
      */
     private String signature() {
         Map<GrailsHibernatePersistentEntity, Class<?>> classes = 
generateGroup(GenCovOwner, GenCovTarget)
@@ -422,13 +424,17 @@ class GrailsDomainGeneratorOptionCoverageSpec extends 
GrailsDomainGeneratorSuppo
     private static String appliedAfterBinding(GrailsDomainGenerator generator, 
GrailsHibernatePersistentEntity entity) {
         return entity.hibernatePersistentProperties.findAll { 
HibernatePersistentProperty property ->
             if (property instanceof HibernateBasicProperty && 
generator.supports(property)) {
-                return generator.collectionFacets((HibernateBasicProperty) 
property).extraLazy()
+                CollectionFacets facets = 
generator.collectionFacets((HibernateBasicProperty) property)
+                return facets.extraLazy() || !facets.indexes().isEmpty()
             }
             if (property instanceof HibernateEmbeddedProperty) {
                 return generator.supports(property) && property.isLazy()
             }
-            return property instanceof HibernateToManyEntityProperty && 
generator.supports(property) &&
-                    generator.toManyFacets((HibernateToManyEntityProperty) 
property).extraLazy()
+            if (property instanceof HibernateToManyEntityProperty && 
generator.supports(property)) {
+                ToManyFacets facets = 
generator.toManyFacets((HibernateToManyEntityProperty) property)
+                return facets.extraLazy() || !facets.indexes().isEmpty()
+            }
+            return false
         }*.name.sort().join(',')
     }
 }
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 2231230110..bd5c144561 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
@@ -19,12 +19,14 @@
 package org.grails.orm.hibernate.cfg.domainbinding.jpa
 
 import grails.gorm.annotation.Entity
+import jakarta.persistence.CollectionTable
 import jakarta.persistence.Table
 import jakarta.persistence.UniqueConstraint
 import org.hibernate.boot.Metadata
 import org.hibernate.mapping.PersistentClass
 
 import 
org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
+import 
org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty
 
 /**
  * Describes how {@link GrailsDomainGenerator} states the unique constraints a 
mapping asks for with {@code unique: 'group'}
@@ -116,18 +118,18 @@ class GrailsDomainGeneratorUniqueGroupSpec extends 
GrailsDomainGeneratorSupport
         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"() {
+    void "a unique group on a collection property states no key, since the key 
the binder makes names columns the collection table does not have"() {
         when:
-        generateGroup(GenUqCollection)
+        Map<GrailsHibernatePersistentEntity, Class<?>> classes = 
generateGroup(GenUqCollection)
+        CollectionTable table = 
classes[entity(GenUqCollection)].getDeclaredField('tags').getAnnotation(CollectionTable)
 
-        then: "the key names a column of the owner's table, which the 
collection table does not have"
-        UnsupportedOperationException e = thrown()
-        e.message.contains('GenUqCollection')
-        e.message.contains('tags')
-        e.message.contains('index or a unique group')
+        then: "the binder's key names a column of the owner's table, so it 
cannot be created; the generated collection has none"
         
entity(GenUqCollection).persistentClass.getProperty('tags').value.collectionTable.uniqueKeys.values().any
 {
             it.columns*.name.contains('x')
         }
+        table.uniqueConstraints().length == 0
+        newGenerator().collectionFacets((HibernateBasicProperty) 
entity(GenUqCollection).getPropertyByName('tags')).indexes().isEmpty()
+        
newGenerator().constraintFacets(entity(GenUqCollection)).uniqueKeys().isEmpty()
     }
 
     private Map<GrailsHibernatePersistentEntity, Class<?>> generateAll() {
diff --git 
a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
 
b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
index 981de8025c..a2af6f4c77 100644
--- 
a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
+++ 
b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
@@ -89,10 +89,6 @@ Nothing is ignored silently. A mapping that boots is bound 
the way it is written
 | `The natural id of [...] names [...], which is not a persistent property of 
the entity ...`
 | Correct the name. Classic binding skips an unknown name without a message, 
so the entity has no natural id.
 
-| An `index` or a `unique` group on the property of a collection (`hasMany`).
-| `Collection property [...]: an index or a unique group is mapped on the 
collection property ...`
-| Remove the option from the collection property and create the index in a 
database migration if you need it. Classic binding creates the index over the 
key column of the collection table, and a `unique` group that names columns of 
the owner's table makes the schema fail to create.
-
 | A `type` on the property of a collection (`hasMany`).
 | `Collection property [...]: a type is mapped on the collection property 
itself ...`
 | Remove the `type`. Classic binding applies it to the collection and to its 
elements alike.
@@ -158,6 +154,12 @@ Some bugs of classic binding are not copied by native 
binding. Native binding do
 
 | The `nullable: false` constraint on the element column of a map of values.
 | Classic binding leaves the column nullable. Native binding makes it `not 
null`.
+
+| A `unique` group on the property of a collection (`hasMany`).
+| The group names columns of the owner's table, which the table of the 
collection does not have. Classic binding tries to create a unique key over 
them and the statement fails when the schema is created, so the database has no 
such key. Native binding creates no key. The `index` option on the same 
property works in both bindings: the index is created over the key column of 
the collection table (and over the element column of a collection of enums), 
with the name the mapping gives it.
+
+| An `index` given as a closure on the property of a collection, for example 
`index: { column name: 'position' }`.
+| The closure configures the index column of a list or a map in both bindings. 
Classic binding also creates an index of the collection table that is named 
after the closure, a name that changes on every start. Native binding creates 
the index column and no such index.
 |===
 
 [[nativeDomainBinding-schema]]

Reply via email to