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 849b34f8a1567f6e00adac82aa137504b366f0ab
Author: Walter Duque de Estrada <[email protected]>
AuthorDate: Wed Oct 7 23:39:55 2026 -0500

    feat: accept a map on a many-to-many in native domain binding
    
    The generated mode refused a Map valued hasMany on a bidirectional 
many-to-many. The domain binder makes a map side not inverse whether or not the 
mapping says it owns the relationship, so the map side writes the join table 
(key column, element column and the column of the key of the map, which is part 
of the primary key), a Set on the other side is inverse over the same table, 
and two maps are two independent tables. The generated classes now state 
exactly that: the map side is the o [...]
    
    Two maps read back as the binder does, a map stores its rows through its 
own side only, which is documented rather than improved. The element column of 
a map beside a set that belongs to the map's class is nullable or not null in 
the binder depending on the order the classes are bound in, which the generated 
mode does not copy: it states not null, and the difference is a known class of 
the DDL differential with the pinning spec. The refused group count of the DDL 
differential drops fr [...]
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../domainbinding/jpa/GrailsDomainGenerator.groovy |  20 +-
 .../GeneratedDomainClassesMapManyToManySpec.groovy | 273 +++++++++++++++++++++
 .../binder/ManyToManyWithoutOwnerSpec.groovy       |  41 +---
 ...eneratedDomainClassesDdlDifferentialSpec.groovy |   6 +-
 .../jpa/GrailsDomainGeneratorSpec.groovy           |  40 ++-
 .../advancedGORMFeatures/nativeDomainBinding.adoc  |  11 +-
 6 files changed, 343 insertions(+), 48 deletions(-)

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 6511ef7da6..7ca78ef1da 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
@@ -1670,6 +1670,15 @@ class GrailsDomainGenerator {
         return order.indexOf(property.name) <= order.indexOf(inverse.name)
     }
 
+    /**
+     * Whether the binder binds the collection of this many-to-many side as 
the one that writes the join table: the owning side
+     * ({@code belongsTo}), and a map, which {@code MapSecondPassBinder} 
always makes not inverse (a map side stores its rows with
+     * the key of the map whether or not the mapping says it owns the 
relationship).
+     */
+    private static boolean ownsManyToMany(HibernateManyToManyProperty 
property) {
+        return property.owningSide || Map.isAssignableFrom(property.type)
+    }
+
     /**
      * @return why the generator cannot describe the collection of entities, 
or {@code null} when it can
      */
@@ -1679,9 +1688,6 @@ class GrailsDomainGenerator {
         if (writeProblem != null) {
             return writeProblem
         }
-        if (Map.isAssignableFrom(property.type) && property instanceof 
HibernateManyToManyProperty) {
-            return 'a map on a many-to-many, which the generator does not 
support yet'
-        }
         CollectionKind kind = CollectionKind.of(property.type)
         if (kind == null) {
             return "the declared type [${property.type?.name}] is not one of 
Set, SortedSet, List or Collection, " +
@@ -1707,10 +1713,10 @@ class GrailsDomainGenerator {
         }
         if (property instanceof HibernateManyToManyProperty) {
             HibernateAssociation other = property.hibernateInverseSide
-            if (!(other instanceof HibernateManyToManyProperty) || 
Map.isAssignableFrom(other.type)) {
+            if (!(other instanceof HibernateManyToManyProperty)) {
                 return "the other side [${other?.name}] is not a many-to-many 
collection"
             }
-            if (!property.owningSide && !other.owningSide) {
+            if (!ownsManyToMany(property) && 
!ownsManyToMany((HibernateManyToManyProperty) other)) {
                 return 'neither side of the many-to-many owns it (no 
belongsTo): the binder binds both collections inverse, so ' +
                         'no row is ever written, and annotations cannot say it 
(Hibernate\'s annotation binder fails with a ' +
                         'NullPointerException when both sides are mappedBy)'
@@ -1802,7 +1808,7 @@ class GrailsDomainGenerator {
             // ManyToOneBinder binds the element like the other side's own 
column: its name rules and its (never) nullable column
             element = circularKeyName(other, toOneColumnFacets(other))
             String joinColumnName = joinTable?.column?.name
-            if (joinColumnName != null && property.owningSide && 
!property.isCircular()) {
+            if (joinColumnName != null && ownsManyToMany(property) && 
!property.isCircular()) {
                 // the owning side names the element column of the join table 
it writes (the inverse side adopts it); a circular
                 // side keeps naming it after the property of the other side, 
as the binder does
                 element = new ColumnFacets(
@@ -1810,7 +1816,7 @@ class GrailsDomainGenerator {
                         element.length(), element.precision(), 
element.scale(), element.sqlType(), element.defaultValue(),
                         element.read(), element.write(), element.comment())
             }
-            mappedBy = property.owningSide ? null : other.name
+            mappedBy = ownsManyToMany(property) ? null : other.name
         } else if (property.shouldBindWithForeignKey()) {
             HibernateToOneProperty inverse = (HibernateToOneProperty) 
property.hibernateInverseSide
             // CollectionKeyBinder copies the other side's foreign key column 
into the key; the key updater makes it nullable
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMapManyToManySpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMapManyToManySpec.groovy
new file mode 100644
index 0000000000..2e5fc4cd45
--- /dev/null
+++ 
b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMapManyToManySpec.groovy
@@ -0,0 +1,273 @@
+/*
+ *  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
+import org.grails.orm.hibernate.cfg.domainbinding.binder.MapMapLeft
+import org.grails.orm.hibernate.cfg.domainbinding.binder.MapMapRight
+import org.grails.orm.hibernate.cfg.domainbinding.binder.MapSetLeft
+import org.grails.orm.hibernate.cfg.domainbinding.binder.MapSetRight
+
+/**
+ * A {@code Map} on a many-to-many, bound by the domain binder and by the 
generated classes. The domain binder makes a map side not
+ * inverse whether or not the mapping says it owns the relationship, so the 
map side writes the join table (key column, element
+ * column and the column of the key of the map, which is part of the primary 
key), a {@code Set} on the other side is inverse and reads
+ * the same table, and two maps are two independent tables (a map on a 
many-to-many stores through its own side only). The generated
+ * classes state exactly that.
+ */
+class GeneratedDomainClassesMapManyToManySpec 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:mmm${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, and which collection of 
which role is inverse. */
+    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 ->
+                            boolean nullable = column.nullable && 
!(table.primaryKey != null && 
table.primaryKey.columns*.name.contains(column.name))
+                            [(column.name): 
"${column.getSqlType(booted.metadata)}${nullable ? '' : ' not 
null'}${column.unique ? ' unique' : ''}".toString()]
+                        },
+                        primaryKey : table.primaryKey?.columns*.name?.sort(),
+                        foreignKeys: table.foreignKeys.values().collect { 
"${it.columns*.name} -> ${it.referencedTable.name}".toString() }.sort(),
+                        indexes    : table.indexes.values().collectEntries { 
[(it.name): it.columns*.name] },
+                        uniqueKeys : table.uniqueKeys.values().collect { 
it.columns*.name.sort() }.sort { it.toString() },
+                ]
+            }
+        }
+        result['collections'] = 
booted.metadata.collectionBindings.collectEntries { 
org.hibernate.mapping.Collection collection ->
+            [(collection.role): "${collection.class.simpleName} 
inverse=${collection.inverse} table=${collection.collectionTable.name} 
key=${collection.key.selectables*.text}".toString()]
+        }.sort()
+        return result
+    }
+
+    @Unroll
+    void "#label: the generated mode creates the schema of the domain 
binder"() {
+        when:
+        Map<String, Map> binder = schema(group, false)
+        Map<String, Map> generated = schema(group, true)
+
+        then:
+        generated == binder
+        generated.keySet() - 'collections' == tables as Set
+        generated[joinTable].columns.keySet() == columns as Set
+        generated[joinTable].primaryKey == primaryKey.sort(false)
+
+        where:
+        label                                          | group                 
      | tables                                                                  
      | joinTable                | columns                                      
                   | primaryKey
+        'a map beside a set'                           | [MapSetLeft, 
MapSetRight]   | ['map_set_left', 'map_set_right', 'map_set_left_rights']       
               | 'map_set_left_rights'    | ['map_set_left_id', 
'map_set_right_id', 'rights_idx']           | ['map_set_left_id', 'rights_idx']
+        'a map beside a map'                           | [MapMapLeft, 
MapMapRight]   | ['map_map_left', 'map_map_right', 'map_map_left_rights', 
'map_map_right_lefts'] | 'map_map_right_lefts'  | ['map_map_left_id', 
'map_map_right_id', 'lefts_idx']            | ['map_map_right_id', 'lefts_idx']
+        'a map beside a set that belongs to the map'   | [MmmOwnerLeft, 
MmmOwnedRight] | ['mmm_owner_left', 'mmm_owned_right', 'mmm_owner_left_rights'] 
             | 'mmm_owner_left_rights'  | ['mmm_owner_left_id', 
'mmm_owned_right_id', 'rights_idx']       | ['mmm_owner_left_id', 'rights_idx']
+        'a map beside a set that owns the relationship' | [MmmOwnedLeft, 
MmmOwnerRight] | ['mmm_owned_left', 'mmm_owner_right', 'mmm_owned_left_rights', 
'mmm_owner_right_lefts'] | 'mmm_owned_left_rights' | ['mmm_owned_left_id', 
'mmm_owner_right_id', 'rights_idx'] | ['mmm_owned_left_id', 'rights_idx']
+        'a map with a join table, key, column and index names' | 
[MmmNamedLeft, MmmNamedRight] | ['mmm_named_left', 'mmm_named_right', 
'mmm_named_join']              | 'mmm_named_join'         | ['l_fk', 'r_fk', 
'k_col']                                      | ['l_fk', 'k_col']
+    }
+
+    void "the map side writes the join table and the set side is inverse"() {
+        when:
+        Map<String, Map> generated = schema([MapSetLeft, MapSetRight], true)
+
+        then:
+        
generated.collections['org.grails.orm.hibernate.cfg.domainbinding.binder.MapSetLeft.rights'].contains('inverse=false')
+        
generated.collections['org.grails.orm.hibernate.cfg.domainbinding.binder.MapSetRight.lefts'].contains('inverse=true')
+        
generated.collections['org.grails.orm.hibernate.cfg.domainbinding.binder.MapSetRight.lefts'].contains('table=map_set_left_rights')
+    }
+
+    @Unroll
+    void "#label: the rows are stored through the map, read back, changed and 
deleted, the same in both modes"() {
+        when:
+        Map<Boolean, Map> results = [false, true].collectEntries { boolean 
generated ->
+            boot(group, generated)
+            [(generated): cycle(left, right, joinTable)]
+        }
+
+        then:
+        results[true] == results[false]
+        results[true].stored == [a: 'r1', b: 'r2']
+        results[true].changed == [b: 'r2', c: 'r1']
+        results[true].rowsStored == 2
+        results[true].rowsChanged == 2
+        results[true].rowsDeleted == 0
+        results[true].inverse == inverse
+
+        where:
+        label                           | group                         | left 
         | right          | joinTable               | inverse
+        'a map beside a set'            | [MapSetLeft, MapSetRight]     | 
MapSetLeft    | MapSetRight    | 'map_set_left_rights'   | ['left']
+        'a map beside a map'            | [MapMapLeft, MapMapRight]     | 
MapMapLeft    | MapMapRight    | 'map_map_left_rights'   | []
+        'a map beside a set it owns'    | [MmmOwnerLeft, MmmOwnedRight] | 
MmmOwnerLeft  | MmmOwnedRight  | 'mmm_owner_left_rights' | ['left']
+        'a map beside an owning set'    | [MmmOwnedLeft, MmmOwnerRight] | 
MmmOwnedLeft  | MmmOwnerRight  | 'mmm_owned_left_rights' | []
+        'a map with a join table named' | [MmmNamedLeft, MmmNamedRight] | 
MmmNamedLeft  | MmmNamedRight  | 'mmm_named_join'        | ['left']
+    }
+
+    void "the domain binder leaves the element column of a map nullable or not 
null depending on the order the classes are bound in, the generated mode always 
states not null"() {
+        when: "the column is shared by the element of the map and the key of 
the set that reads it, and the binder sets its nullability twice"
+        Map<String, String> binder = [[MmmOwnerLeft, MmmOwnedRight], 
[MmmOwnedRight, MmmOwnerLeft]].collectEntries { List<Class> group ->
+            [(group*.simpleName.join(',')): schema(group, 
false)['mmm_owner_left_rights'].columns['mmm_owned_right_id']]
+        }
+        Map<String, String> generated = [[MmmOwnerLeft, MmmOwnedRight], 
[MmmOwnedRight, MmmOwnerLeft]].collectEntries { List<Class> group ->
+            [(group*.simpleName.join(',')): schema(group, 
true)['mmm_owner_left_rights'].columns['mmm_owned_right_id']]
+        }
+
+        then:
+        binder.values().toSet() == ['bigint', 'bigint not null'].toSet()
+        generated.values().toSet() == ['bigint not null'].toSet()
+    }
+
+    private Map cycle(Class left, Class right, String joinTable) {
+        Long leftId
+        Long firstId
+        left.withTransaction {
+            def first = right.newInstance(name: 'r1').save(failOnError: true)
+            def second = right.newInstance(name: 'r2').save(failOnError: true)
+            firstId = first.id
+            leftId = left.newInstance(name: 'left', rights: [a: first, b: 
second]).save(failOnError: true, flush: true).id
+        }
+        Map stored = left.withNewSession { new 
TreeMap(left.get(leftId).rights.collectEntries { String key, value -> [key, 
value.name] }) }
+        List inverse = right.withNewSession {
+            def side = right.get(firstId).lefts
+            side instanceof Map ? side.values()*.name.sort() : 
side*.name.sort()
+        }
+        int rowsStored = countRows(joinTable)
+        left.withTransaction {
+            def row = left.get(leftId)
+            def first = right.get(firstId)
+            row.rights.remove('a')
+            row.rights.put('c', first)
+            row.save(failOnError: true, flush: true)
+        }
+        Map changed = left.withNewSession { new 
TreeMap(left.get(leftId).rights.collectEntries { String key, value -> [key, 
value.name] }) }
+        int rowsChanged = countRows(joinTable)
+        left.withTransaction { left.get(leftId).delete(flush: true) }
+        return [stored: stored, inverse: inverse, changed: changed, 
rowsStored: rowsStored, rowsChanged: rowsChanged, rowsDeleted: 
countRows(joinTable)]
+    }
+
+    private int countRows(String table) {
+        
datastore.connectionSources.defaultConnectionSource.dataSource.connection.withCloseable
 { java.sql.Connection connection ->
+            connection.createStatement().executeQuery("select count(*) from 
${table}".toString()).with { java.sql.ResultSet rows -> rows.next(); 
rows.getInt(1) }
+        }
+    }
+
+    void "a query joins through the map and through the set that reads it, the 
same in both modes"() {
+        when:
+        List<List> results = [false, true].collect { boolean generated ->
+            boot([MapSetLeft, MapSetRight], generated)
+            MapSetLeft.withTransaction {
+                MapSetRight red = new MapSetRight(name: 
'red').save(failOnError: true)
+                MapSetRight blue = new MapSetRight(name: 
'blue').save(failOnError: true)
+                new MapSetLeft(name: 'one', rights: [x: red, y: 
blue]).save(failOnError: true)
+                new MapSetLeft(name: 'two', rights: [x: 
red]).save(failOnError: true, flush: true)
+            }
+            MapSetLeft.withNewSession {
+                [MapSetLeft.executeQuery('select l.name from MapSetLeft l join 
l.rights r where r.name = :n order by l.name', [n: 'red']),
+                 MapSetLeft.executeQuery('select l.name from MapSetLeft l join 
l.rights r where r.name = :n', [n: 'blue']),
+                 MapSetRight.executeQuery('select l.name from MapSetRight r 
join r.lefts l where r.name = :n order by l.name', [n: 'red']),
+                 MapSetLeft.executeQuery('select count(l) from MapSetLeft l 
where size(l.rights) = 2')[0]]
+            }
+        }
+
+        then:
+        results[1] == results[0]
+        results[1] == [['one', 'two'], ['one'], ['one', 'two'], 1]
+    }
+
+    void "the second map of two maps does not see the rows stored through the 
first, in both modes"() {
+        when:
+        List<List> results = [false, true].collect { boolean generated ->
+            boot([MapMapLeft, MapMapRight], generated)
+            MapMapLeft.withTransaction {
+                MapMapRight right = new MapMapRight(name: 
'right').save(failOnError: true)
+                new MapMapLeft(name: 'left', rights: [first: 
right]).save(failOnError: true, flush: true)
+            }
+            MapMapLeft.withNewSession { 
[MapMapLeft.findByName('left').rights.keySet() as List, 
MapMapRight.findByName('right').lefts.keySet() as List] }
+        }
+
+        then:
+        results[1] == results[0]
+        results[1] == [['first'], []]
+    }
+}
+
+@Entity
+class MmmOwnerLeft {
+    String name
+    Map<String, MmmOwnedRight> rights
+    static hasMany = [rights: MmmOwnedRight]
+}
+
+@Entity
+class MmmOwnedRight {
+    String name
+    Set<MmmOwnerLeft> lefts
+    static hasMany = [lefts: MmmOwnerLeft]
+    static belongsTo = MmmOwnerLeft
+}
+
+@Entity
+class MmmOwnedLeft {
+    String name
+    Map<String, MmmOwnerRight> rights
+    static hasMany = [rights: MmmOwnerRight]
+    static belongsTo = MmmOwnerRight
+}
+
+@Entity
+class MmmOwnerRight {
+    String name
+    Set<MmmOwnedLeft> lefts
+    static hasMany = [lefts: MmmOwnedLeft]
+}
+
+@Entity
+class MmmNamedLeft {
+    String name
+    Map<String, MmmNamedRight> rights
+    static hasMany = [rights: MmmNamedRight]
+    static mapping = {
+        rights joinTable: [name: 'mmm_named_join', key: 'l_fk', column: 
'r_fk'], indexColumn: [name: 'k_col']
+    }
+}
+
+@Entity
+class MmmNamedRight {
+    String name
+    Set<MmmNamedLeft> lefts
+    static hasMany = [lefts: MmmNamedLeft]
+}
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy
index 901ec72f7c..1301ce7c9c 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy
@@ -67,20 +67,6 @@ class ManyToManyWithoutOwnerSpec extends Specification {
         return null
     }
 
-    private static UnsupportedOperationException refusalFailure(Closure<?> 
boot) {
-        try {
-            boot()
-        } catch (Throwable e) {
-            for (Throwable cause = e; cause != null; cause = cause.cause == 
cause ? null : cause.cause) {
-                if (cause instanceof UnsupportedOperationException) {
-                    return (UnsupportedOperationException) cause
-                }
-            }
-            throw e
-        }
-        return null
-    }
-
     @Unroll
     def "the application does not start when neither side of a many-to-many 
declares belongsTo (generated mapping: #generated)"() {
         when:
@@ -158,9 +144,9 @@ class ManyToManyWithoutOwnerSpec extends Specification {
     }
 
     @Unroll
-    def "a many-to-many with a Map on #shape starts without belongsTo and 
stores its rows through the Map side"() {
+    def "a many-to-many with a Map on #shape starts without belongsTo and 
stores its rows through the Map side (generated mapping: #generated)"() {
         when:
-        boot(false, left, right)
+        boot(generated, left, right)
         left.withTransaction {
             def rightRow = right.newInstance(name: 'right').save(failOnError: 
true)
             left.newInstance(name: 'left', (leftProperty): [first: 
rightRow]).save(flush: true, failOnError: true)
@@ -171,24 +157,11 @@ class ManyToManyWithoutOwnerSpec extends Specification {
         !readsBack || right.withNewSession { 
right.findByName('right')."$rightProperty"*.name } == ['left']
 
         where:
-        shape        | left       | right       | leftProperty | rightProperty 
| readsBack
-        'one side'   | MapSetLeft | MapSetRight | 'rights'     | 'lefts'       
| true
-        'both sides' | MapMapLeft | MapMapRight | 'rights'     | 'lefts'       
| false
-    }
-
-    @Unroll
-    def "the generated mapping refuses a many-to-many with a Map on #shape as 
a map on a many-to-many, not as a missing belongsTo"() {
-        when:
-        UnsupportedOperationException refusal = refusalFailure { boot(true, 
left, right) }
-
-        then:
-        refusal != null
-        refusal.message.contains('a map on a many-to-many, which the generator 
does not support yet')
-
-        where:
-        shape        | left       | right
-        'one side'   | MapSetLeft | MapSetRight
-        'both sides' | MapMapLeft | MapMapRight
+        shape        | left       | right       | leftProperty | rightProperty 
| readsBack | generated
+        'one side'   | MapSetLeft | MapSetRight | 'rights'     | 'lefts'       
| true      | false
+        'both sides' | MapMapLeft | MapMapRight | 'rights'     | 'lefts'       
| false     | false
+        'one side'   | MapSetLeft | MapSetRight | 'rights'     | 'lefts'       
| true      | true
+        'both sides' | MapMapLeft | MapMapRight | 'rights'     | 'lefts'       
| false     | true
     }
 
     def "a Set on both sides without belongsTo still does not start"() {
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 edc0b72504..f0cc67926e 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
@@ -69,6 +69,7 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
             [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_MANY_TO_MANY_ELEMENT_ORDER', reason: 'A binder defect 
that depends on the order the classes are bound in: the element column of a map 
on a many-to-many is also the key column of the set that reads the map, one 
column of the join table, and the binder sets its nullability twice (the 
element binder: not null; the key updater of the inverse set: nullable), so a 
database created by the binder has a nullable column or a not null one 
depending on which of the two collecti [...]
             [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 [...]
@@ -87,7 +88,6 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
             'which is HibernateEmbeddedProperty',
             'which is not a persistent property of the entity',
             'is a registered type with type parameters',
-            'a map on a many-to-many',
     ]
 
     private static final AtomicInteger BOOTS = new AtomicInteger()
@@ -178,6 +178,10 @@ class GeneratedDomainClassesDdlDifferentialSpec extends 
Specification {
         if (kind == 'unique key only in binder mode' && d.impossibleKey) {
             return 'UNIQUE_GROUP_ON_COLLECTION'
         }
+        if (collection && kind == 'column nullable' && 
detail.contains('binder=true generated=false') &&
+                d.collections*.startsWith('Map of ManyToOne').any() && 
d.collections*.endsWith('(inverse)').any()) {
+            return 'MAP_MANY_TO_MANY_ELEMENT_ORDER'
+        }
         if (collection && kind in ['column nullable', 'primary key only in 
generated mode', 'unique key only in binder mode']) {
             return 'COLLECTION_TABLE_KEY'
         }
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorSpec.groovy
index 5f107fb16e..6834603cca 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorSpec.groovy
@@ -167,7 +167,7 @@ class GrailsDomainGeneratorSpec extends 
HibernateGormDatastoreSpec {
                 GenFkTarget, GenFkOwned, GenFkOwner, GenFkCascades, 
GenFkNodeA, GenFkNodeB, GenFkHasOneOwner, GenFkHasOneDetail, GenOneFace, 
GenOneNose, GenFkManyOne, GenFkOneSide, GenFkSub, GenFkSubRoot,
                 GenOmParent, GenOmChild, GenOmListed, GenOmOrdered, 
GenOmOrphan, GenOmFetched, GenOmTag, GenOmStep, GenOmKept, GenOmSortedOwner, 
GenOmMapOwner, GenMapBidiOwner, GenMapBidiChild, GenEmbAssocOwner,
                 GenMmStudent, GenMmCourse, GenMmPerson, GenParamsOnly, 
GenDecimal, GenUnversioned, GenUnversionedRoot, GenUnversionedChild, 
GenConverted, GenValueTyped,
-                GenCollEmbeddedHolder, GenCollEmbeddedSibling, 
GenCollEmbeddedItem, GenCollEmbeddedEntityHolder)
+                GenCollEmbeddedHolder, GenCollEmbeddedSibling, 
GenCollEmbeddedItem, GenCollEmbeddedEntityHolder, GenMapM2mLeft, GenMapM2mRight)
     }
 
     List<StandardServiceRegistry> registries = []
@@ -1902,6 +1902,26 @@ class GrailsDomainGeneratorSpec extends 
HibernateGormDatastoreSpec {
         GenMapBidiOwner | 'kids'   | GenMapBidiChild | 
'gen_map_bidi_owner_kids' | 'kids_id' | 'owner_id'              | 'kids_idx'
     }
 
+    void "a map on a many-to-many is the side that writes the join table, with 
a map key column, and the set that reads it is mappedBy"() {
+        given:
+        Map<GrailsHibernatePersistentEntity, Class<?>> classes = 
generateGroup(GenMapM2mLeft, GenMapM2mRight)
+        Field rights = 
classes[entity(GenMapM2mLeft)].getDeclaredField('rights')
+        Field lefts = classes[entity(GenMapM2mRight)].getDeclaredField('lefts')
+
+        expect:
+        rights.genericType.typeName == 'java.util.Map<java.lang.String, ' + 
GenMapM2mRight.name + '>'
+        rights.getAnnotation(ManyToMany).mappedBy() == ''
+        rights.getAnnotation(JoinTable).name() == 'gen_map_m2m_left_rights'
+        rights.getAnnotation(JoinTable).joinColumns()*.name() == 
['gen_map_m2m_left_id']
+        rights.getAnnotation(JoinTable).inverseJoinColumns()*.name() == 
['gen_map_m2m_right_id']
+        rights.getAnnotation(MapKeyColumn).name() == 'rights_idx'
+        lefts.genericType.typeName == 'java.util.Set<' + GenMapM2mLeft.name + 
'>'
+        lefts.getAnnotation(ManyToMany).mappedBy() == 'rights'
+        !lefts.isAnnotationPresent(JoinTable)
+        
newGenerator().supports(entity(GenMapM2mLeft).getHibernatePropertyByName('rights'))
+        
newGenerator().supports(entity(GenMapM2mRight).getHibernatePropertyByName('lefts'))
+    }
+
     void "an association inside an embedded type is a field of the embeddable, 
and each owner states its join column with @AssociationOverride"() {
         given:
         Map<GrailsHibernatePersistentEntity, Class<?>> classes = 
generateGroup(GenEmbAssocOwner, GenFkTarget)
@@ -3347,3 +3367,21 @@ class GenUnversionedChild extends GenUnversionedRoot {
 
     String extra
 }
+
+@Entity
+class GenMapM2mLeft {
+
+    String name
+    Map<String, GenMapM2mRight> rights
+
+    static hasMany = [rights: GenMapM2mRight]
+}
+
+@Entity
+class GenMapM2mRight {
+
+    String name
+    Set<GenMapM2mLeft> lefts
+
+    static hasMany = [lefts: GenMapM2mLeft]
+}
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 97c796475c..42b70ef4d9 100644
--- 
a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
+++ 
b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
@@ -61,6 +61,7 @@ For the domain classes in GORM's own test suites, both 
bindings produce the same
 * A `hasMany` of basic values whose `type` is `'serializable'` or a `UserType` 
class is stored in one column of the owner's table, as before, with the 
`index`, `unique` group and column settings of the property. A `type` on a 
`hasMany` of domain classes changes nothing in both bindings.
 * An `index` on the property of a `hasMany` is created over the key column of 
the collection table (and over the element column of a collection of enums), 
and `indexColumn` may give the index of a list or the key of a map a `type` 
other than integer or string.
 * A `hasMany` inside a class listed in `static embedded` (basic values, enums 
or domain classes, also in a nested embedded class) is stored in a collection 
table named after the embedded class, not after the owner, with a key column 
named after the embedded class too, as with classic binding.
+* A `Map` on a many-to-many (`Map<String, Book> books` with a `Set` or another 
`Map` on the other side) writes its own join table, with the key column of the 
map as part of the primary key, as with classic binding. A `Set` on the other 
side reads that table and does not write it, and two maps are two separate 
tables: rows stored through one map are not visible through the other, in both 
bindings.
 * Identifier generators, inheritance strategies (single table, joined and 
table-per-concrete-class), discriminators, natural ids, optimistic locking, 
lazy and eager fetching, cascades, sorting, batch size and `cache` usage are 
mapped as with classic binding.
 
 [[nativeDomainBinding-refused]]
@@ -96,10 +97,6 @@ Nothing is ignored silently. A mapping that boots is bound 
the way it is written
 | `Collection property [...]: the type [...] mapped on the collection property 
names neither a class nor serializable ...` or `... a custom collection type (a 
UserCollectionType) is mapped on the collection property ...`
 | Remove the `type`, or use `'serializable'` or a `UserType` class to store 
the collection in one column. Classic binding does not boot with a registered 
type name (it fails with `Could not load requested class`); a custom collection 
type is not described yet.
 
-| A `Map` on a many-to-many.
-| `Association property [...]: a map on a many-to-many ...`
-| Use a `Set` or `List` many-to-many, or model the join with a domain class of 
its own.
-
 | A `type` that is a registered Hibernate type name for a different Java type 
than the property, for example `type: 'serializable'` on a `String`.
 | `Type [serializable] of property [...] is registered for the Java type 
[java.io.Serializable], not the property's [java.lang.String] ...`
 | Use a `UserType` class, or a type name registered for the property's own 
type.
@@ -168,7 +165,7 @@ Some bugs of classic binding are not copied by native 
binding. Native binding do
 [[nativeDomainBinding-schema]]
 === Differences in the Schema
 
-The schema of 679 groups of related domain classes was created with both 
bindings on H2 and compared: tables, columns with type, nullability, default, 
length, precision and scale, primary keys with their column order, foreign 
keys, unique keys, indexes, check constraints and sequences. Apart from the 10 
groups that native binding refuses, these are the differences. Other databases 
are not covered by this comparison, so verify against your own database as 
described below.
+The schema of 685 groups of related domain classes was created with both 
bindings on H2 and compared: tables, columns with type, nullability, default, 
length, precision and scale, primary keys with their column order, foreign 
keys, unique keys, indexes, check constraints and sequences. Apart from the 8 
groups that native binding refuses, these are the differences. Other databases 
are not covered by this comparison, so verify against your own database as 
described below.
 
 [cols="2,3,3", options="header"]
 |===
@@ -196,6 +193,10 @@ The schema of 679 groups of related domain classes was 
created with both binding
 | Classic binding creates a second table for the inverse side that nothing 
reads or writes. Native binding uses the table that the owning side names.
 | The second table stays in an existing database. Remove it yourself.
 
+| `not null` on the column of a `Map` on a many-to-many that holds the entity 
the map refers to, when the other side is a `Set`.
+| That column is also the key column of the `Set` that reads the map, and 
classic binding sets its nullability twice, so it is nullable or not null 
depending on the order in which the domain classes are bound. Native binding 
always creates it `not null`, like the element column of any many-to-many.
+| `update` does not change an existing nullable column. A diff reports the 
difference.
+
 | `not null` on the element column of a map of values mapped with `nullable: 
false`.
 | See <<nativeDomainBinding-behavior,Differences in Behavior>>.
 | `update` does not change an existing nullable column. A diff reports the 
difference.

Reply via email to