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 81c7bd95b2887078129e8ce2171b2032a667221e Author: Walter Duque de Estrada <[email protected]> AuthorDate: Thu Oct 8 15:33:06 2026 -0500 feat: accept composite identifiers in many-to-many, maps and partly mapped foreign keys in native domain binding The generated mode refused a many-to-many or a map of entities that involves an entity with a composite identifier, and a foreign key to a composite identifier whose mapping names fewer columns than the identifier has properties. The domain binder boots all of them: the join table has a key column for each identifier property of the owner and an element column for each one of the target, the columns the mapping names keep their names in order, and the missing ones are named as the bin [...] Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../jpa/GeneratedDomainClassBinder.groovy | 10 +- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 73 +++- .../cfg/domainbinding/jpa/ToManyFacets.groovy | 9 +- ...atedDomainClassesCompositeCollectionSpec.groovy | 430 +++++++++++++++++++++ .../unbootable/CompositeIdUnbootableDomains.groovy | 23 -- .../GrailsDomainGeneratorCompositeIdSpec.groovy | 5 +- .../GrailsDomainGeneratorDifferentialSpec.groovy | 4 +- .../advancedGORMFeatures/nativeDomainBinding.adoc | 5 +- 8 files changed, 505 insertions(+), 54 deletions(-) diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy index a7ea5399c1..975e37967c 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 @@ -675,7 +675,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { ToManyFacets facets = generator.toManyFacets((HibernateToManyEntityProperty) property, qualifier) alignJoinColumns(collection.key, facets.keys()) if (facets.manyToMany()) { - alignJoinColumns(collection.element, [facets.element()]) + alignJoinColumns(collection.element, facets.elements()) } } else if (property instanceof HibernateBasicProperty) { alignJoinColumns(collection.key, generator.collectionFacets((HibernateBasicProperty) property, qualifier).keys()) @@ -789,15 +789,15 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { return } List<ColumnFacets> keys - ColumnFacets element + List<ColumnFacets> elements if (property instanceof HibernateToManyEntityProperty) { ToManyFacets facets = generator.toManyFacets((HibernateToManyEntityProperty) property, qualifier) keys = facets.keys() - element = facets.element() + elements = facets.elements() } else if (property instanceof HibernateBasicProperty) { CollectionFacets facets = generator.collectionFacets((HibernateBasicProperty) property, qualifier) keys = facets.keys() - element = facets.element() + elements = [facets.element()] } else { return } @@ -807,7 +807,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { table.primaryKey = null } restoreNullability(collection.key, keys) - restoreNullability(collection.element, [element]) + restoreNullability(collection.element, elements) if (rederive) { collection.createAllKeys() } 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 ec7dd95929..c0fa89f916 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 @@ -1302,6 +1302,10 @@ class GrailsDomainGenerator { } } + private static final String severalKeyColumns = 'the mapping states several columns for the key of a collection of an entity with a ' + + 'simple identifier: the binder gives the key as many columns as the mapping states and Hibernate refuses the foreign key ' + + "('Foreign key must have the same number of columns as the referenced primary key'), so the application does not start" + /** * @return why the generator cannot describe the collection of basic values, or {@code null} when it can */ @@ -1333,6 +1337,8 @@ class GrailsDomainGenerator { if (compositeProblem != null) { return compositeProblem } + } else if (mapped.columns != null && mapped.columns.size() > 1) { + return severalKeyColumns } boolean isEnum = property instanceof HibernateEnumProperty if (isEnum && kind == CollectionKind.MAP) { @@ -1369,11 +1375,7 @@ class GrailsDomainGenerator { } } } - if (property instanceof HibernateManyToManyProperty || Map.isAssignableFrom(property.type)) { - return 'the owner or the associated entity has a composite identifier, and the collection is a many-to-many or a map: the ' + - 'generator does not describe the key and element columns of those yet' - } - if (compositeIdentifier(target) && !property.shouldBindWithForeignKey()) { + if (compositeIdentifier(target) && !property.shouldBindWithForeignKey() && !(property instanceof HibernateManyToManyProperty)) { return 'the associated entity has a composite identifier and the collection is bound through a join table: the binder gives ' + 'the element columns from the column configs of the collection property, which it reads again for the key, so the ' + 'key gets the element\'s columns' @@ -1771,6 +1773,10 @@ class GrailsDomainGenerator { return compositeProblem } } + if (!compositeIdentifier(property.hibernateOwner) && !property.shouldBindWithForeignKey() && + mapped.columns != null && mapped.columns.size() > 1) { + return severalKeyColumns + } if (property.isUserButNotCollectionType()) { return 'a class is mapped as the type of the collection property, which the binder binds as one column of the owner\'s table ' + 'that holds the collection, and Hibernate fails to boot for a collection of entities' @@ -1852,6 +1858,8 @@ class GrailsDomainGenerator { ColumnFacets key List<ColumnFacets> keys = null ColumnFacets element = null + List<ColumnFacets> elements = null + List<String> referencedElements = [] boolean manyToMany = true if (property instanceof HibernateManyToManyProperty) { HibernateManyToManyProperty other = (HibernateManyToManyProperty) property.hibernateInverseSide @@ -1863,8 +1871,28 @@ class GrailsDomainGenerator { if (!boundBeforeInverseSide((HibernateManyToManyProperty) property)) { key = circularKeyName((HibernateManyToManyProperty) property, key) } + if (compositeIdentifier(property.hibernateOwner)) { + // DependentKeyValueBinder: one key column for each identifier property of the owner + keys = collectionKeyColumns(property) + key = keys[0] + } // ManyToOneBinder binds the element like the other side's own column: its name rules and its (never) nullable column - element = circularKeyName(other, toOneColumnFacets(other)) + // (named by the other side's column rules alone: the other side refers to this owner, whose identifier may be composite) + element = circularKeyName(other, toOneColumnFacets(other, '', firstColumnConfig(other.hibernateMappedForm))) + if (compositeIdentifier(target)) { + // the element is a foreign key to a composite identifier: one column for each identifier property of the target + if (ownsManyToMany(property)) { + elements = compositeForeignKeyConfigs(property, target, false).collect { ColumnConfig columnConfig -> + toOneColumnFacets(other, '', columnConfig) + } + referencedElements = compositeReferencedColumns(target) + } else { + // the inverse side reads the table of the owning side: its element columns are the key columns of the owner + elements = collectionKeyColumns((HibernateManyToManyProperty) other) + referencedElements = collectionKeyReferencedColumns((HibernateManyToManyProperty) other) + } + element = elements[0] + } String joinColumnName = joinTable?.column?.name 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 @@ -1932,7 +1960,9 @@ class GrailsDomainGenerator { keys != null ? collectionKeyReferencedColumns(property) : [], collectionIndexType(property, kind), collectionTableIndexes(property, table, keys != null ? keys : [key], element), - mapped.type != null && property.userType != null && UserCollectionType.isAssignableFrom(property.userType) ? property.userType : null) + mapped.type != null && property.userType != null && UserCollectionType.isAssignableFrom(property.userType) ? property.userType : null, + element == null ? [] : (elements != null ? elements : [element]), + referencedElements) } /** @@ -2007,9 +2037,10 @@ class GrailsDomainGenerator { } List<ColumnConfig> columns = property.hibernateMappedForm.columns int expected = foreignKeyColumnCount.calculateForeignKeyColumnCount(root, root.hibernateCompositeIdentity.get().propertyNames) - if (!columns.isEmpty() && (columns.size() != expected || columns.any { ColumnConfig cc -> cc.name == null })) { - return "the mapping states ${columns.size()} columns (or leaves one unnamed) for a foreign key to a composite identifier " + - "with ${expected} properties: the binder fills the missing ones and the generator does not reproduce that yet" + if (columns.size() > expected) { + return "the mapping states ${columns.size()} columns for a foreign key to a composite identifier with ${expected} " + + 'properties: the binder fails with an IndexOutOfBoundsException or Hibernate refuses the foreign key because it has ' + + 'more columns than the key' } return null } @@ -2020,11 +2051,9 @@ class GrailsDomainGenerator { * names one for each identifier property after the table of the associated entity and the default column name of the * identifier property. */ - private List<ColumnConfig> compositeForeignKeyConfigs(HibernateAssociation property, GrailsHibernatePersistentEntity target) { - List<ColumnConfig> columns = property.hibernateMappedForm.columns - if (!columns.isEmpty()) { - return columns - } + private List<ColumnConfig> compositeForeignKeyConfigs( + HibernateAssociation property, GrailsHibernatePersistentEntity target, boolean useMappedColumns = true) { + List<ColumnConfig> mapped = useMappedColumns ? property.hibernateMappedForm.columns : [] GrailsHibernatePersistentEntity root = target.hibernateRootEntity String prefix = root.getTableName(namingStrategy) List<ColumnConfig> generated = [] @@ -2043,7 +2072,15 @@ class GrailsDomainGenerator { generated << new ColumnConfig(name: foreignKeyColumnName(prefix, suffix)) } } - return generated + if (mapped.isEmpty()) { + return generated + } + // the binder keeps the columns the mapping states, in order, and names the missing ones as it would have named all of them + List<ColumnConfig> result = new ArrayList<ColumnConfig>(mapped) + if (mapped.size() < generated.size()) { + result.addAll(generated.drop(mapped.size())) + } + return result } private static String foreignKeyColumnName(String... parts) { @@ -2766,7 +2803,7 @@ class GrailsDomainGenerator { AnnotationDescription.Builder joinTable = AnnotationDescription.Builder.ofType(JpaJoinTable) .define('name', facets.tableName()) .defineAnnotationArray('joinColumns', TypeDescription.ForLoadedType.of(JoinColumn), keyJoinColumns(facets.keys(), facets.referencedKeys())) - .defineAnnotationArray('inverseJoinColumns', TypeDescription.ForLoadedType.of(JoinColumn), joinColumnAnnotation(facets.element())) + .defineAnnotationArray('inverseJoinColumns', TypeDescription.ForLoadedType.of(JoinColumn), keyJoinColumns(facets.elements(), facets.referencedElements())) if (facets.schema()) { joinTable = joinTable.define('schema', facets.schema()) } @@ -3079,7 +3116,7 @@ class GrailsDomainGenerator { joinTable = AnnotationDescription.Builder.ofType(JpaJoinTable) .define('name', facets.tableName()) .defineAnnotationArray('joinColumns', TypeDescription.ForLoadedType.of(JoinColumn), keyJoinColumns(facets.keys(), facets.referencedKeys())) - .defineAnnotationArray('inverseJoinColumns', TypeDescription.ForLoadedType.of(JoinColumn), joinColumnAnnotation(facets.element())) + .defineAnnotationArray('inverseJoinColumns', TypeDescription.ForLoadedType.of(JoinColumn), keyJoinColumns(facets.elements(), facets.referencedElements())) if (facets.schema()) { joinTable = joinTable.define('schema', facets.schema()) } 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 29f2be2f79..a92bb94d26 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 @@ -62,6 +62,11 @@ import org.hibernate.FetchMode * <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> * + * <p>{@code elements} are the element columns of a join table in the order the binder binds them: one, or one for each identifier + * property when the associated entity has a composite identifier ({@code element} is the first of them); {@code referencedElements} + * names the column of the associated entity's key each one points at, and is empty unless that entity has a composite identifier. + * Both are empty when the collection has no join table.</p> + * * @since 9.0 */ @CompileStatic @@ -89,5 +94,7 @@ record ToManyFacets( List<String> referencedKeys, TypeFacets indexType, List<IndexFacets> indexes, - Class<?> collectionType = null) { + Class<?> collectionType = null, + List<ColumnFacets> elements = [], + List<String> referencedElements = []) { } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeCollectionSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeCollectionSpec.groovy new file mode 100644 index 0000000000..b7f94351e4 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeCollectionSpec.groovy @@ -0,0 +1,430 @@ +/* + * 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 + * + * http://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 + +/** + * Many-to-many associations and maps of entities that involve an entity with a composite identifier, and foreign keys to a composite + * identifier that the mapping gives fewer columns than the identifier has properties. The domain binder boots them: it gives the join + * table a key column for each identifier property of the owner and an element column for each one of the target, names the columns the + * mapping states in order and names the missing ones as it would have named all of them. The generated mode describes the same tables + * and columns instead of refusing the mapping. + */ +class GeneratedDomainClassesCompositeCollectionSpec 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:gcc${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.generatedDomainClasses': generated, + ], group as Class[]) + return datastore + } + + /** The tables of the boot model: columns with type and nullability (a primary key column is not null), primary key and foreign 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) { + List<String> key = table.primaryKey?.columns*.name ?: [] + result[table.name] = [ + columns : table.columns.collectEntries { org.hibernate.mapping.Column column -> + [(column.name): "${column.getSqlType(booted.metadata)}${column.nullable && !key.contains(column.name) ? '' : ' not null'}".toString()] + }, + primaryKey : key.sort(), + foreignKeys: table.foreignKeys.values().collect { "${it.columns*.name} -> ${it.referencedTable.name}".toString() }.sort(), + ] + } + } + return result + } + + @Unroll + void "#label: the generated mode creates the tables and columns of the domain binder"() { + when: + Map<String, Map> binder = schema(group, false) + Map<String, Map> generated = schema(group, true) + + then: + generated == binder + generated[table].columns.keySet() == columns as Set + + where: + label | group | table | columns + 'a many-to-many owned by a composite identifier' | [GccCompOwner, GccOther] | 'gcc_comp_owner_others' | ['gcc_other_id', 'gcc_comp_owner_a', 'gcc_comp_owner_b'] + 'a many-to-many to a composite identifier' | [GccSimple, GccCompTarget] | 'gcc_simple_comps' | ['gcc_simple_id', 'gcc_comp_target_a', 'gcc_comp_target_b'] + 'a many-to-many between composite identifiers' | [GccLeft, GccRight] | 'gcc_left_rights' | ['gcc_left_a', 'gcc_left_b', 'gcc_right_x', 'gcc_right_y'] + 'a map of entities on both sides' | [GccMapLeft, GccMapRight] | 'gcc_map_left_rights' | ['gcc_map_left_id', 'rights_idx', 'gcc_map_right_a', 'gcc_map_right_b'] + 'a map of entities of a composite owner' | [GccMapOwner, GccItem] | 'gcc_map_owner_items' | ['gcc_item_id', 'gcc_map_owner_a', 'gcc_map_owner_b', 'items_idx'] + 'a many-to-many with the key columns mapped' | [GccMappedLeft, GccMappedRight] | 'gcc_mapped_left_rights' | ['k1', 'k2', 'gcc_mapped_right_x', 'gcc_mapped_right_y'] + 'a foreign key mapped with fewer columns than the key' | [GccPartialRef, GccPartialKey] | 'gcc_partial_ref' | ['id', 'version', 'only_one', 'gcc_partial_key_b'] + 'a collection mapped with one column of two' | [GccPartialTags] | 'gcc_partial_tags_tags' | ['k1', 'gcc_partial_tags_b', 'tags_java_lang_string'] + } + + @Unroll + void "#label: the rows are stored, read back, changed and deleted in both modes"() { + when: + Map<Boolean, List> results = [false, true].collectEntries { boolean generated -> + boot(group, generated) + [(generated): this."${cycle}"()] + } + + then: + results[true] == results[false] + results[true] == expected + + where: + label | group | cycle | expected + 'a many-to-many owned by a composite identifier' | [GccCompOwner, GccOther] | 'ownedCycle' | [['o1', 'o2'], ['o2', 'o3'], ['o2', 'o3']] + 'a many-to-many to a composite identifier' | [GccSimple, GccCompTarget] | 'targetCycle' | [['a1/b1', 'a2/b2'], ['a2/b2', 'a3/b3'], ['a2/b2', 'a3/b3']] + 'a many-to-many between composite identifiers' | [GccLeft, GccRight] | 'betweenCycle' | [['x1/y1', 'x2/y2'], ['x2/y2', 'x3/y3'], ['x2/y2', 'x3/y3']] + 'a map of entities on both sides' | [GccMapLeft, GccMapRight] | 'mapBothCycle' | [[one: 'r1', two: 'r2'], [two: 'r2', three: 'r3']] + 'a map of entities of a composite owner' | [GccMapOwner, GccItem] | 'mapOwnerCycle' | [[one: 'i1', two: 'i2'], [two: 'i2', three: 'i3']] + 'a many-to-many with the key columns mapped' | [GccMappedLeft, GccMappedRight] | 'mappedCycle' | [['x1/y1'], ['x2/y2']] + 'a foreign key mapped with fewer columns than the key' | [GccPartialRef, GccPartialKey] | 'partialCycle' | ['a1/b1', 'a2/b2'] + 'a collection mapped with one column of two' | [GccPartialTags] | 'partialTagsCycle' | [['t1', 't2'], ['t3']] + } + + private List ownedCycle() { + GccCompOwner.withTransaction { + GccOther one = new GccOther(name: 'o1').save(failOnError: true) + GccOther two = new GccOther(name: 'o2').save(failOnError: true) + new GccCompOwner(a: 'a1', b: 'b1', others: [one, two] as Set).save(failOnError: true, flush: true) + } + GccCompOwner key = new GccCompOwner(a: 'a1', b: 'b1') + List first = GccCompOwner.withNewSession { GccCompOwner.get(key).others*.name.sort() } + GccCompOwner.withTransaction { + GccCompOwner owner = GccCompOwner.get(key) + owner.others = [GccOther.findByName('o2'), new GccOther(name: 'o3').save(failOnError: true)] as Set + owner.save(failOnError: true, flush: true) + } + List second = GccCompOwner.withNewSession { GccCompOwner.get(key).others*.name.sort() } + List fromOther = GccOther.withNewSession { GccOther.findAllByNameInList(['o1', 'o2', 'o3']).findAll { it.owners*.a.contains('a1') }*.name.sort() } + return [first, second, fromOther] + } + + private List targetCycle() { + GccSimple.withTransaction { + new GccSimple(comps: [new GccCompTarget(a: 'a1', b: 'b1').save(failOnError: true), new GccCompTarget(a: 'a2', b: 'b2').save(failOnError: true)] as Set) + .save(failOnError: true, flush: true) + } + Long id = GccSimple.withNewSession { GccSimple.list().first().id } + List first = GccSimple.withNewSession { GccSimple.get(id).comps.collect { "${it.a}/${it.b}".toString() }.sort() } + GccSimple.withTransaction { + GccSimple simple = GccSimple.get(id) + simple.comps = [GccCompTarget.get(new GccCompTarget(a: 'a2', b: 'b2')), new GccCompTarget(a: 'a3', b: 'b3').save(failOnError: true)] as Set + simple.save(failOnError: true, flush: true) + } + List second = GccSimple.withNewSession { GccSimple.get(id).comps.collect { "${it.a}/${it.b}".toString() }.sort() } + List fromComp = GccCompTarget.withNewSession { + GccCompTarget.list().findAll { !it.simples.isEmpty() }.collect { "${it.a}/${it.b}".toString() }.sort() + } + return [first, second, fromComp] + } + + private List betweenCycle() { + GccLeft.withTransaction { + new GccLeft(a: 'a1', b: 'b1', rights: [new GccRight(x: 'x1', y: 'y1').save(failOnError: true), new GccRight(x: 'x2', y: 'y2').save(failOnError: true)] as Set) + .save(failOnError: true, flush: true) + } + GccLeft key = new GccLeft(a: 'a1', b: 'b1') + List first = GccLeft.withNewSession { GccLeft.get(key).rights.collect { "${it.x}/${it.y}".toString() }.sort() } + GccLeft.withTransaction { + GccLeft left = GccLeft.get(key) + left.rights = [GccRight.get(new GccRight(x: 'x2', y: 'y2')), new GccRight(x: 'x3', y: 'y3').save(failOnError: true)] as Set + left.save(failOnError: true, flush: true) + } + List second = GccLeft.withNewSession { GccLeft.get(key).rights.collect { "${it.x}/${it.y}".toString() }.sort() } + List fromRight = GccRight.withNewSession { + GccRight.list().findAll { !it.lefts.isEmpty() }.collect { "${it.x}/${it.y}".toString() }.sort() + } + return [first, second, fromRight] + } + + private List mapBothCycle() { + Long id = GccMapLeft.withTransaction { + new GccMapLeft(rights: [one: new GccMapRight(a: 'a1', b: 'b1', label: 'r1').save(failOnError: true), + two: new GccMapRight(a: 'a2', b: 'b2', label: 'r2').save(failOnError: true)]).save(failOnError: true, flush: true).id + } + Map first = GccMapLeft.withNewSession { new TreeMap(GccMapLeft.get(id).rights.collectEntries { k, v -> [(k): v.label] }) } + GccMapLeft.withTransaction { + GccMapLeft left = GccMapLeft.get(id) + left.rights = [two: GccMapRight.get(new GccMapRight(a: 'a2', b: 'b2')), + three: new GccMapRight(a: 'a3', b: 'b3', label: 'r3').save(failOnError: true)] + left.save(failOnError: true, flush: true) + } + Map second = GccMapLeft.withNewSession { new TreeMap(GccMapLeft.get(id).rights.collectEntries { k, v -> [(k): v.label] }) } + return [first, second] + } + + private List mapOwnerCycle() { + GccMapOwner.withTransaction { + new GccMapOwner( + a: 'a1', b: 'b1', + items: [one: new GccItem(label: 'i1').save(failOnError: true), two: new GccItem(label: 'i2').save(failOnError: true)]) + .save(failOnError: true, flush: true) + } + GccMapOwner key = new GccMapOwner(a: 'a1', b: 'b1') + Map first = GccMapOwner.withNewSession { new TreeMap(GccMapOwner.get(key).items.collectEntries { k, v -> [(k): v.label] }) } + GccMapOwner.withTransaction { + GccMapOwner owner = GccMapOwner.get(key) + owner.items = [two: GccItem.findByLabel('i2'), three: new GccItem(label: 'i3').save(failOnError: true)] + owner.save(failOnError: true, flush: true) + } + Map second = GccMapOwner.withNewSession { new TreeMap(GccMapOwner.get(key).items.collectEntries { k, v -> [(k): v.label] }) } + return [first, second] + } + + private List mappedCycle() { + GccMappedLeft.withTransaction { + new GccMappedLeft(a: 'a1', b: 'b1', rights: [new GccMappedRight(x: 'x1', y: 'y1').save(failOnError: true)] as Set).save(failOnError: true, flush: true) + } + GccMappedLeft key = new GccMappedLeft(a: 'a1', b: 'b1') + List first = GccMappedLeft.withNewSession { GccMappedLeft.get(key).rights.collect { "${it.x}/${it.y}".toString() }.sort() } + GccMappedLeft.withTransaction { + GccMappedLeft left = GccMappedLeft.get(key) + left.rights = [new GccMappedRight(x: 'x2', y: 'y2').save(failOnError: true)] as Set + left.save(failOnError: true, flush: true) + } + return [first, GccMappedLeft.withNewSession { GccMappedLeft.get(key).rights.collect { "${it.x}/${it.y}".toString() }.sort() }] + } + + private List partialCycle() { + GccPartialRef.withTransaction { + GccPartialKey first = new GccPartialKey(a: 'a1', b: 'b1').save(failOnError: true) + new GccPartialRef(target: first).save(failOnError: true, flush: true) + } + Long id = GccPartialRef.withNewSession { GccPartialRef.list().first().id } + String first = GccPartialRef.withNewSession { GccPartialRef ref = GccPartialRef.get(id); "${ref.target.a}/${ref.target.b}".toString() } + GccPartialRef.withTransaction { + GccPartialRef ref = GccPartialRef.get(id) + ref.target = new GccPartialKey(a: 'a2', b: 'b2').save(failOnError: true) + ref.save(failOnError: true, flush: true) + } + return [first, GccPartialRef.withNewSession { GccPartialRef ref = GccPartialRef.get(id); "${ref.target.a}/${ref.target.b}".toString() }] + } + + private List partialTagsCycle() { + GccPartialTags.withTransaction { new GccPartialTags(a: 'a1', b: 'b1', tags: ['t1', 't2'] as Set).save(failOnError: true, flush: true) } + GccPartialTags key = new GccPartialTags(a: 'a1', b: 'b1') + List first = GccPartialTags.withNewSession { GccPartialTags.get(key).tags.sort() } + GccPartialTags.withTransaction { + GccPartialTags owner = GccPartialTags.get(key) + owner.tags = ['t3'] as Set + owner.save(failOnError: true, flush: true) + } + return [first, GccPartialTags.withNewSession { GccPartialTags.get(key).tags.sort() }] + } +} + +@Entity +class GccOther { + String name + Set<GccCompOwner> owners + + static hasMany = [owners: GccCompOwner] + static belongsTo = [GccCompOwner] +} + +@Entity +class GccCompOwner implements Serializable { + String a + String b + Set<GccOther> others + + static hasMany = [others: GccOther] + + static mapping = { + id composite: ['a', 'b'] + } +} + +@Entity +class GccSimple { + Set<GccCompTarget> comps + + static hasMany = [comps: GccCompTarget] +} + +@Entity +class GccCompTarget implements Serializable { + String a + String b + Set<GccSimple> simples + + static hasMany = [simples: GccSimple] + static belongsTo = [GccSimple] + + static mapping = { + id composite: ['a', 'b'] + } +} + +@Entity +class GccLeft implements Serializable { + String a + String b + Set<GccRight> rights + + static hasMany = [rights: GccRight] + + static mapping = { + id composite: ['a', 'b'] + } +} + +@Entity +class GccRight implements Serializable { + String x + String y + Set<GccLeft> lefts + + static hasMany = [lefts: GccLeft] + static belongsTo = [GccLeft] + + static mapping = { + id composite: ['x', 'y'] + } +} + +@Entity +class GccMapLeft { + Map<String, GccMapRight> rights + + static hasMany = [rights: GccMapRight] +} + +@Entity +class GccMapRight implements Serializable { + String a + String b + String label + Map<String, GccMapLeft> lefts + + static hasMany = [lefts: GccMapLeft] + static belongsTo = [GccMapLeft] + + static mapping = { + id composite: ['a', 'b'] + } +} + +@Entity +class GccItem { + String label +} + +@Entity +class GccMapOwner implements Serializable { + String a + String b + Map<String, GccItem> items + + static hasMany = [items: GccItem] + + static mapping = { + id composite: ['a', 'b'] + } +} + +@Entity +class GccMappedLeft implements Serializable { + String a + String b + Set<GccMappedRight> rights + + static hasMany = [rights: GccMappedRight] + + static mapping = { + id composite: ['a', 'b'] + columns { + rights { + column name: 'k1' + column name: 'k2' + } + } + } +} + +@Entity +class GccMappedRight implements Serializable { + String x + String y + Set<GccMappedLeft> lefts + + static hasMany = [lefts: GccMappedLeft] + static belongsTo = [GccMappedLeft] + + static mapping = { + id composite: ['x', 'y'] + } +} + +@Entity +class GccPartialKey implements Serializable { + String a + String b + + static mapping = { + id composite: ['a', 'b'] + } +} + +@Entity +class GccPartialRef { + GccPartialKey target + + static mapping = { + target column: 'only_one' + } +} + +@Entity +class GccPartialTags implements Serializable { + String a + String b + Set<String> tags + + static hasMany = [tags: String] + + static mapping = { + id composite: ['a', 'b'] + columns { + tags { + column name: 'k1' + } + } + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/CompositeIdUnbootableDomains.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/CompositeIdUnbootableDomains.groovy index 533688231c..2f399d9182 100644 --- a/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/CompositeIdUnbootableDomains.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/CompositeIdUnbootableDomains.groovy @@ -43,29 +43,6 @@ class UnbootableJoinToComposite { static hasMany = [targets: UnbootableComposite] } -@Entity -class UnbootableMmComposite implements Serializable { - - String a - String b - Set<UnbootableMmOther> others - - static hasMany = [others: UnbootableMmOther] - - static mapping = { - id composite: ['a', 'b'] - } -} - -@Entity -class UnbootableMmOther { - - Set<UnbootableMmComposite> composites - - static hasMany = [composites: UnbootableMmComposite] - static belongsTo = [UnbootableMmComposite] -} - @Entity class UnbootableTarget { diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorCompositeIdSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorCompositeIdSpec.groovy index d8f8c9bd85..9b402987ea 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorCompositeIdSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorCompositeIdSpec.groovy @@ -51,8 +51,6 @@ import grails.unbootable.UnbootableRefToTop import grails.unbootable.UnbootableTarget import grails.unbootable.UnbootableTop import grails.unbootable.UnbootableJoinToComposite -import grails.unbootable.UnbootableMmComposite -import grails.unbootable.UnbootableMmOther import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity /** @@ -219,7 +217,7 @@ class GrailsDomainGeneratorCompositeIdSpec extends GrailsDomainGeneratorSupport } } - void "a collection to an entity with a composite identifier that the generator cannot describe is rejected by name"() { + void "a join table to an entity with a composite identifier is rejected by name, because the binder cannot boot it"() { when: newGenerator().generateAll(unbound(domain, composite), getClass().classLoader) @@ -232,7 +230,6 @@ class GrailsDomainGeneratorCompositeIdSpec extends GrailsDomainGeneratorSupport where: domain | composite | property | reason UnbootableJoinToComposite | UnbootableComposite | 'targets' | 'join table' - UnbootableMmOther | UnbootableMmComposite | 'composites' | 'many-to-many' } void "a foreign key to a composite identifier inside an embedded type is stated with an association override for each column"() { 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 80c50c5d98..56a6cea4ef 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 @@ -1772,7 +1772,9 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { "${where} ${facet}: generator=${values[0]} binder=${values[1]}".toString() }) // 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(compareValueColumns( + "${where} element".toString(), facets.elements().isEmpty() ? [facets.element()] : facets.elements(), collection.element, + collection.collectionTable, true)) found.addAll(compareCollectionTableIndexes( where, facets.indexes(), collection, property instanceof HibernateManyToManyProperty && property.bidirectional, known)) } 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 32ca4c4d1e..49f072df83 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -72,6 +72,7 @@ For the domain classes in GORM's own test suites, both bindings produce the same * A `discriminator` column may set `precision` and `scale`. They change nothing in the DDL of a string, integer or character column, in both bindings. * A multi-tenant id (`tenantId`) may have a mapped `type`: its column has the type, and the tenant filter still compares it with the current tenant. * The `defaultValue`, `comment`, `read` and `write` of the column mapping of an association or of a `hasMany` are put on the foreign key column (on the key column of a collection, and on the element column of a many-to-many for the options of the other side). The `length`, `precision` and `scale` change nothing: a foreign key column has the type of the column it references, and a `hasMany` of basic values ignores them too. This is the same in both bindings. +* A many-to-many or a map of domain classes may involve an entity with a composite identifier on either side or on both: the join table has a key column for each identifier property of the owner and an element column for each one of the target, named as with classic binding. A foreign key to a composite identifier that the mapping gives fewer columns than the identifier has properties keeps the columns the mapping names and names the missing ones as classic binding does. * 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]] @@ -95,9 +96,9 @@ 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 a collection of basic values ...` | 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`), and neither with a custom collection type on a collection of basic values. -| A composite identifier that is combined with something the mapping does not state faithfully: a many-to-many, a map or a join table that involves an entity with a composite identifier, a composite identifier part that is the inverse side of a one-to-one, a foreign key mapped with a different number of columns than the identifier has properties, or a composite identifier referring to a deeply nested composite identifier. +| A composite identifier combined with something that classic binding cannot boot either: a `hasMany` of domain classes with a join table to an entity with a composite identifier (a many-to-many and a map of a many-to-many are fine), a join table whose key columns are mapped on an entity with a composite identifier, a composite identifier part that is the inverse side of a one-to-one, a part that refers to an entity with a simple identifier or to a composite identifier more than one leve [...] | `... composite identifier ...`, naming the entity and the part. -| Give the entity a single-column identifier, or map the relationship with a domain class of its own. +| Give the entity a single-column identifier, or map the relationship with a domain class of its own. Classic binding fails with `Foreign key ... must have same number of columns as the referenced primary key` or an `IndexOutOfBoundsException`. | An association mapped with a `formula`, or with several columns where the target does not have a composite identifier. | `... the association is mapped with a formula` or `... the mapping states several columns ...`
