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 a43950e5e0e23517956b13d43008281b2ca1bb3e Author: Walter Duque de Estrada <[email protected]> AuthorDate: Tue Oct 6 15:11:52 2026 -0500 feat: fail at startup for a many-to-many that neither side owns When neither side of a bidirectional many-to-many declares belongsTo, both collections are bound inverse and no join table row is ever written, which loses data silently. On 9.0, a major release, the application now refuses to start with a MappingException that names both sides and tells the user where to declare belongsTo, instead of choosing an owner or only logging a warning. A self-referencing many-to-many without belongsTo stores nothing either (probed), so it fails too; unidirectional ones and ones with an owning side are unaffected. The generated mapping raises the same error before the generator refuses the shape. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../domainbinding/binder/CollectionBinder.groovy | 2 + .../binder/ManyToManyOwnerValidator.groovy | 73 ++++++++ .../jpa/GeneratedDomainClassBinder.groovy | 17 ++ .../ManyToManyWithoutOwnerDomains.groovy | 54 ++++++ .../binder/ManyToManyWithoutOwnerSpec.groovy | 191 +++++++++++++++++++++ 5 files changed, 337 insertions(+) diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.groovy index 356a63604e..ead0dddf26 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.groovy +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.groovy @@ -68,6 +68,7 @@ class CollectionBinder { final MapSecondPassBinder mapSecondPassBinder private final InFlightMetadataCollector mappings private final TableForManyCalculator tableForManyCalculator + private final ManyToManyOwnerValidator manyToManyOwnerValidator = new ManyToManyOwnerValidator() void setComponentBinder(ComponentBinder componentBinder) { this.collectionSecondPassBinder.setComponentBinder(componentBinder) @@ -162,6 +163,7 @@ class CollectionBinder { } private void bindCollectionTable(HibernateToManyProperty property, Collection collection) { + manyToManyOwnerValidator.validate(property) String tableName = tableForManyCalculator.getTableName(property) String schemaName = tableForManyCalculator.getJoinTableSchema(property) String catalogName = tableForManyCalculator.getJoinTableCatalog(property) diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyOwnerValidator.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyOwnerValidator.groovy new file mode 100644 index 0000000000..a7bab181dc --- /dev/null +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyOwnerValidator.groovy @@ -0,0 +1,73 @@ +/* + * 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 org.grails.orm.hibernate.cfg.domainbinding.binder + +import groovy.transform.CompileStatic +import org.hibernate.MappingException + +import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateAssociation +import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyProperty +import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty + +/** + * A bidirectional many-to-many is written by its owning side, which {@code belongsTo} designates. When neither side + * declares it, both collections are bound inverse and the relationship is never stored, which loses data silently. The + * application refuses to start with such a mapping instead. + * + * <p>The rule covers a self-referencing many-to-many too: its sides are owning only when the class declares itself in + * {@code belongsTo}, and without that both are inverse as well. A unidirectional many-to-many, and one where either side + * owns the relationship, are accepted.</p> + * + * @since 9.0 + */ +@CompileStatic +class ManyToManyOwnerValidator { + + /** + * @param property a property of an entity about to be bound + * @throws MappingException when the property is one side of a bidirectional many-to-many that neither side owns + */ + void validate(HibernatePersistentProperty property) { + if (!(property instanceof HibernateManyToManyProperty)) { + return + } + HibernateManyToManyProperty manyToMany = (HibernateManyToManyProperty) property + if (!manyToMany.isBidirectional() || manyToMany.isOwningSide()) { + return + } + HibernateAssociation otherSide = manyToMany.hibernateInverseSide + if (!(otherSide instanceof HibernateManyToManyProperty) || otherSide.isOwningSide()) { + return + } + // the same message whichever side is bound first: the sides are named in alphabetical order + HibernateAssociation first = manyToMany + HibernateAssociation second = otherSide + if (describe(first) > describe(second)) { + first = otherSide + second = manyToMany + } + throw new MappingException("Neither side of the many-to-many between [${describe(first)}] and [${describe(second)}] " + + 'declares belongsTo, so the relationship would never be stored. Declare belongsTo on the owned side, ' + + "for example in ${second.owner.javaClass.simpleName}: static belongsTo = ${first.owner.javaClass.simpleName}") + } + + private static String describe(HibernateAssociation side) { + return "${side.owner.name}.${side.name}" + } +} 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 59427ba450..816385c27c 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 @@ -53,6 +53,7 @@ import org.grails.datastore.mapping.model.types.Embedded import org.grails.orm.hibernate.cfg.HibernateSimpleIdentity import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy import org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnConfigToColumnBinder +import org.grails.orm.hibernate.cfg.domainbinding.binder.ManyToManyOwnerValidator import org.grails.orm.hibernate.cfg.domainbinding.binder.NumericColumnConstraintsBinder import org.grails.orm.hibernate.cfg.domainbinding.binder.PropertyBinder import org.grails.orm.hibernate.cfg.domainbinding.binder.StringColumnConstraintsBinder @@ -148,6 +149,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { return } requireTargetsOnTheDataSource(toGenerate) + requireOwnedManyToMany(toGenerate) // GORM's dirty checking reads the 'derived' flag the domain binder sets on the mapping of a formula property for (GrailsHibernatePersistentEntity entity : toGenerate) { entity.configureDerivedProperties() @@ -241,6 +243,21 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { } } + /** + * A many-to-many that neither side owns would never be stored: the domain binder refuses it at startup, and so does this + * binder, with the same message, before the generator reports the mapping as one it cannot express. + */ + private static void requireOwnedManyToMany(List<GrailsHibernatePersistentEntity> entities) { + ManyToManyOwnerValidator validator = new ManyToManyOwnerValidator() + for (GrailsHibernatePersistentEntity entity : entities) { + for (PersistentProperty<?> property : entity.persistentProperties) { + if (property instanceof HibernatePersistentProperty) { + validator.validate((HibernatePersistentProperty) property) + } + } + } + } + private List<GrailsHibernatePersistentEntity> hierarchies(List<HibernatePersistentEntity> entities) { List<GrailsHibernatePersistentEntity> result = [] Deque<GrailsHibernatePersistentEntity> pending = new ArrayDeque<GrailsHibernatePersistentEntity>() diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/ManyToManyWithoutOwnerDomains.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/ManyToManyWithoutOwnerDomains.groovy new file mode 100644 index 0000000000..23236dc04a --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/ManyToManyWithoutOwnerDomains.groovy @@ -0,0 +1,54 @@ +/* + * 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.unbootable + +import grails.gorm.annotation.Entity + +/** + * Bidirectional many-to-many relationships that no side owns (no {@code belongsTo}), kept outside the packages the + * differential specs scan: the application refuses to start with them. + */ +@Entity +class NoOwnerLeft { + + String name + Set<NoOwnerRight> rights + + static hasMany = [rights: NoOwnerRight] +} + +@Entity +class NoOwnerRight { + + String name + Set<NoOwnerLeft> lefts + + static hasMany = [lefts: NoOwnerLeft] +} + +@Entity +class NoOwnerSelf { + + String name + Set<NoOwnerSelf> followers + Set<NoOwnerSelf> following + + static hasMany = [followers: NoOwnerSelf, following: NoOwnerSelf] + static mappedBy = [followers: 'following', following: 'followers'] +} 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 new file mode 100644 index 0000000000..327af3ce89 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy @@ -0,0 +1,191 @@ +/* + * 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 org.grails.orm.hibernate.cfg.domainbinding.binder + +import grails.gorm.annotation.Entity +import grails.unbootable.NoOwnerLeft +import grails.unbootable.NoOwnerRight +import grails.unbootable.NoOwnerSelf +import org.grails.datastore.mapping.core.DatastoreUtils +import org.grails.orm.hibernate.HibernateDatastore +import org.hibernate.MappingException +import org.hibernate.dialect.H2Dialect +import spock.lang.AutoCleanup +import spock.lang.Specification +import spock.lang.Unroll + +/** + * A bidirectional many-to-many is written by the side that {@code belongsTo} designates as the owner. When neither side + * declares it, both collections are inverse and the relationship is never stored, so the application refuses to start + * instead of silently losing the data, in both the domain binder and the generated mapping. + */ +class ManyToManyWithoutOwnerSpec extends Specification { + + @AutoCleanup + HibernateDatastore datastore + + private HibernateDatastore boot(boolean generated, Class... classes) { + datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([ + 'dataSource.url' : "jdbc:h2:mem:m2mNoOwner${generated}${System.nanoTime()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'dataSource.dialect' : H2Dialect.name, + 'hibernate.hbm2ddl.auto' : 'create-drop', + 'hibernate.cache.queries' : 'false', + 'hibernate.cache.use_query_cache' : 'false', + 'hibernate.generatedDomainClasses': generated, + ]), classes) + return datastore + } + + private static MappingException mappingFailure(Closure<?> boot) { + try { + boot() + } catch (Throwable e) { + for (Throwable cause = e; cause != null; cause = cause.cause == cause ? null : cause.cause) { + if (cause instanceof MappingException) { + return (MappingException) 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: + MappingException failure = mappingFailure { boot(generated, NoOwnerLeft, NoOwnerRight) } + + then: 'the message names both sides and says where to declare belongsTo' + failure != null + failure.message == 'Neither side of the many-to-many between [grails.unbootable.NoOwnerLeft.rights] and ' + + '[grails.unbootable.NoOwnerRight.lefts] declares belongsTo, so the relationship would never be stored. ' + + 'Declare belongsTo on the owned side, for example in NoOwnerRight: static belongsTo = NoOwnerLeft' + + where: + generated << [false, true] + } + + @Unroll + def "the application does not start when a self-referencing many-to-many has no belongsTo (generated mapping: #generated)"() { + when: + MappingException failure = mappingFailure { boot(generated, NoOwnerSelf) } + + then: + failure != null + failure.message.contains('[grails.unbootable.NoOwnerSelf.followers] and [grails.unbootable.NoOwnerSelf.following]') + failure.message.contains('static belongsTo = NoOwnerSelf') + + where: + generated << [false, true] + } + + @Unroll + def "a many-to-many with belongsTo on one side starts and stores its rows (generated mapping: #generated)"() { + when: + boot(generated, OwnedLeft, OwnerRight) + OwnerRight.withTransaction { + OwnerRight owner = new OwnerRight(name: 'owner') + owner.addToLefts(new OwnedLeft(name: 'left')) + owner.save(flush: true, failOnError: true) + } + + then: + OwnerRight.withNewSession { OwnerRight.first().lefts*.name } == ['left'] + OwnedLeft.withNewSession { OwnedLeft.first().owners*.name } == ['owner'] + + where: + generated << [false, true] + } + + @Unroll + def "a unidirectional many-to-many starts (generated mapping: #generated)"() { + when: + boot(generated, UnidirectionalLeft, UnidirectionalRight) + + then: + noExceptionThrown() + + where: + generated << [false, true] + } + + @Unroll + def "a self-referencing many-to-many with belongsTo starts and stores its rows (generated mapping: #generated)"() { + when: + boot(generated, OwnedSelf) + OwnedSelf.withTransaction { + OwnedSelf first = new OwnedSelf(name: 'first') + first.addToFollowers(new OwnedSelf(name: 'second')) + first.save(flush: true, failOnError: true) + } + + then: + OwnedSelf.withNewSession { OwnedSelf.findByName('first').followers*.name } == ['second'] + + where: + generated << [false, true] + } +} + +@Entity +class OwnedLeft { + + String name + Set<OwnerRight> owners + + static hasMany = [owners: OwnerRight] + static belongsTo = OwnerRight +} + +@Entity +class OwnerRight { + + String name + Set<OwnedLeft> lefts + + static hasMany = [lefts: OwnedLeft] +} + +@Entity +class UnidirectionalLeft { + + String name + Set<UnidirectionalRight> rights + + static hasMany = [rights: UnidirectionalRight] +} + +@Entity +class UnidirectionalRight { + + String name +} + +@Entity +class OwnedSelf { + + String name + Set<OwnedSelf> followers + Set<OwnedSelf> following + + static hasMany = [followers: OwnedSelf, following: OwnedSelf] + static mappedBy = [followers: 'following', following: 'followers'] + static belongsTo = [OwnedSelf] +}
