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 8f77322ec3f46a743521651c1695e23632c32a1f Author: Walter Duque de Estrada <[email protected]> AuthorDate: Wed Oct 7 23:14:39 2026 -0500 feat: accept a collection inside an embedded type in native domain binding The generated mode refused every hasMany inside a class listed in static embedded. The domain binder names the collection table after the embedded class and not after the owner (and the key column too, pointing at the owner's table), which the property's own facets already state, so the collections of basic values, enums and entities (also in a nested embedded class) are now bound as element collections and to-many associations of the generated embeddable. Two defects of the first attempt are fixed: a collection was listed as an attribute override leaf of the owner and renamed its element column, and a collection of entities inside an embeddable made Hibernate retry a failed element type check forever, so the embeddable that holds one takes the name of the embedded class like an entity. The one case still refused, by a precise message, is a collection of an embedded type reachable through more than one embedded property: the binder binds a single table whose key points at only one owner, and fails to boot when the properties are named alike. The refused group count of the DDL differential drops from 12 to 10, and the differential now compares the collections inside components. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 73 +++- ...ratedDomainClassesEmbeddedCollectionSpec.groovy | 445 +++++++++++++++++++++ .../unbootable/EmbeddedCollectionDomains.groovy | 32 ++ ...eneratedDomainClassesDdlDifferentialSpec.groovy | 1 - .../GrailsDomainGeneratorDifferentialSpec.groovy | 41 +- .../jpa/GrailsDomainGeneratorSpec.groovy | 108 ++++- .../advancedGORMFeatures/nativeDomainBinding.adoc | 9 +- 7 files changed, 693 insertions(+), 16 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 c9442c0e33..6511ef7da6 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 @@ -279,6 +279,10 @@ class GrailsDomainGenerator { for (GrailsHibernatePersistentEntity entity : given) { requireReferencedEntities(entity, given) } + String collision = embeddedCollectionCollision(given) + if (collision != null) { + throw new UnsupportedOperationException(collision) + } List<GrailsHibernatePersistentEntity> ordered = new ArrayList<GrailsHibernatePersistentEntity>(given) ordered.sort { GrailsHibernatePersistentEntity a, GrailsHibernatePersistentEntity b -> depth(a) <=> depth(b) } @@ -305,6 +309,53 @@ class GrailsDomainGenerator { return result } + /** + * The binder names the table and the key column of a collection inside an embedded type after the embedded type and not after + * the owner, and gives it no owner-specific identity, so two embedded properties that share a type with a collection share one + * table whose key is a foreign key to the owner that was bound first (probed: the rows of the other owner violate it unless the + * identifiers happen to coincide), and Hibernate refuses the duplicate collection at boot when the two properties have the same name + * (pinned in {@code GrailsDomainBinderEmbeddedCollectionDefectSpec}). One embedded property per type is described exactly as the + * binder binds it; a second one is rejected by name rather than described with a table the generator would have to invent. + * + * @return why the embedded properties of the entities cannot be described together, or {@code null} when no collection of an + * embedded type is reachable through more than one embedded property + */ + private static String embeddedCollectionCollision(Collection<GrailsHibernatePersistentEntity> entities) { + Map<String, List<String>> uses = new LinkedHashMap<String, List<String>>() + for (GrailsHibernatePersistentEntity entity : entities) { + for (HibernatePersistentProperty property : entity.persistentPropertiesToBind) { + if (property instanceof HibernateEmbeddedProperty) { + collectCollectionUses((HibernateEmbeddedProperty) property, "${entity.name}.${property.name}".toString(), uses, []) + } + } + } + Map.Entry<String, List<String>> shared = uses.entrySet().find { Map.Entry<String, List<String>> use -> use.value.size() > 1 } + if (shared == null) { + return null + } + String[] parts = shared.key.split('#') + return "The collection [${parts[1]}] of the embedded type [${parts[0]}] is reachable through ${shared.value.size()} embedded " + + "properties (${shared.value.join(', ')}): the binder names its table and its key column after the embedded type and not " + + 'after the owner, so the owners share one table whose key is a foreign key to only one of them, and Hibernate refuses ' + + 'the duplicate collection at boot when the properties have the same name (pinned in ' + + 'GrailsDomainBinderEmbeddedCollectionDefectSpec), which the generator does not copy and annotations cannot say' + } + + private static void collectCollectionUses( + HibernateEmbeddedProperty property, String path, Map<String, List<String>> uses, List<Class<?>> visiting) { + GrailsHibernatePersistentEntity type = (GrailsHibernatePersistentEntity) property.associatedEntity + if (type == null || visiting.contains(type.javaClass)) { + return + } + for (HibernatePersistentProperty peer : embeddedPeers(property)) { + if (peer instanceof HibernateEmbeddedProperty) { + collectCollectionUses((HibernateEmbeddedProperty) peer, "${path}.${peer.name}".toString(), uses, visiting + [type.javaClass]) + } else if (peer instanceof HibernateToManyProperty) { + uses.computeIfAbsent("${type.javaClass.name}#${peer.name}".toString()) { String key -> new ArrayList<String>() }.add(path) + } + } + } + private static void requireWholeHierarchy(GrailsHibernatePersistentEntity entity, Set<GrailsHibernatePersistentEntity> given) { if (!entity.isRoot() && superEntity(entity, given) == null) { throw new IllegalArgumentException( @@ -2152,6 +2203,9 @@ class GrailsDomainGenerator { String path = relative.isEmpty() ? peer.name : "${relative}.${peer.name}".toString() if (peer instanceof HibernateEmbeddedProperty) { collectLeaves((HibernateEmbeddedProperty) peer, currentPath, path, enclosing, leaves) + } else if (peer instanceof HibernateToManyProperty) { + // a collection has a table of its own and no column in the owner's table: the embeddable states its table and columns itself + continue } else if (isDerived(peer)) { leaves << new EmbeddedLeaf(path, peer, null, null) } else if (peer instanceof HibernateToOneProperty && compositeIdentifier(((HibernateToOneProperty) peer).hibernateAssociatedEntity)) { @@ -2237,10 +2291,9 @@ class GrailsDomainGenerator { return problem } } else if (peer instanceof HibernateToManyProperty) { - return "the property [${peer.name}] of [${type.name}] is a collection inside an embedded type: the binder names its table and " + - 'its key column after the embedded type and not after the owner, so two owners of the type collide ' + - 'and Hibernate refuses the duplicate collection at boot (pinned in GrailsDomainBinderEmbeddedCollectionDefectSpec), ' + - 'which the generator does not copy and annotations cannot say' + if (!supports(peer)) { + return unsupportedReason(type, peer) + } } else if (peer instanceof HibernateToOneProperty) { if (!boundAsManyToOne((HibernateToOneProperty) peer)) { return "the property [${peer.name}] of [${type.name}] is the inverse side of a one-to-one inside an embedded type, " + @@ -2969,9 +3022,19 @@ class GrailsDomainGenerator { if (existing != null) { return existing.typeDescription } - String base = generatedEmbeddableName(type) + // Hibernate checks the declared element type of a collection of entities against the class it finds for the declaring type by + // name, and retries a failed check without end. It finds the class generated for an entity under the entity's name, which has + // no getters to check, but would find the real class of an embedded type with its getters and the generated class of the + // entity as the element type, so the embeddable that holds such a collection takes the name of the embedded type like an entity. + boolean holdsEntities = peers.any { HibernatePersistentProperty peer -> peer instanceof HibernateToManyEntityProperty } + String base = holdsEntities ? type.javaClass.name : generatedEmbeddableName(type) String name = base int variant = 1 + if (holdsEntities && embeddables.values().any { DynamicType.Unloaded<?> other -> other.typeDescription.name == name }) { + throw new UnsupportedOperationException( + "The embedded type [${type.name}] holds a collection of entities and is embedded with two different sets of " + + 'properties, which the generator cannot describe: Hibernate needs the class generated for it to carry the name of the type') + } while (embeddables.values().any { DynamicType.Unloaded<?> other -> other.typeDescription.name == name }) { name = base + '_' + (++variant) } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedCollectionSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedCollectionSpec.groovy new file mode 100644 index 0000000000..f28322dd1a --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedCollectionSpec.groovy @@ -0,0 +1,445 @@ +/* + * 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 grails.unbootable.EmbeddedCollectionOwnerA +import grails.unbootable.EmbeddedCollectionOwnerB +import grails.unbootable.EmbeddedCollectionOwnerC +import grails.unbootable.EmbeddedCollectionOwnerD +import org.hibernate.mapping.Table +import spock.lang.AutoCleanup +import spock.lang.Specification +import spock.lang.Unroll + +import org.grails.orm.hibernate.HibernateDatastore + +/** + * A collection inside an embedded type, bound by the domain binder and by the generated classes. The domain binder names the table + * of such a collection after the embedded type and not after the owner ({@code ecs_words_words}), and its key column after the + * embedded type too ({@code ecs_words_id}), whatever the embedded property is called; the key points at the table of the owner. The + * generated classes state the same names. Two embedded properties that share a type with a collection would share that one table, + * which the binder cannot make sense of, so the generated mode rejects them by name. + */ +class GeneratedDomainClassesEmbeddedCollectionSpec 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:ecs${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: columns with SQL type and nullability, keys, foreign keys, indexes, unique keys. */ + private Map<String, Map> schema(List<Class> group, boolean generated) { + HibernateDatastore booted = boot(group, generated) + Map<String, Map> result = new TreeMap<String, Map>() + for (Table table : booted.metadata.collectTableMappings()) { + if (table.physicalTable) { + result[table.name] = [ + columns : table.columns.collectEntries { org.hibernate.mapping.Column column -> + 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() }, + ] + } + } + 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() == tables as Set + generated[table].columns.keySet() == columns as Set + + where: + label | group | tables | table | columns + 'a set of strings' | [EcsSetOwner] | ['ecs_set_owner', 'ecs_words_words'] | 'ecs_words_words' | ['ecs_words_id', 'words_java_lang_string'] + 'a set beside simple properties' | [EcsMixedOwner] | ['ecs_mixed_owner', 'ecs_mixed_words_words'] | 'ecs_mixed_words_words' | ['ecs_mixed_words_id', 'words_java_lang_string'] + 'a set of enums' | [EcsEnumOwner] | ['ecs_enum_owner', 'ecs_enums_colors'] | 'ecs_enums_colors' | ['ecs_enums_id', 'ecs_color'] + 'a set mapped with a join table' | [EcsNamedOwner] | ['ecs_named_owner', 'ecs_named_words'] | 'ecs_named_words' | ['owner_fk', 'word_col'] + 'a set in a nested embedded type' | [EcsNestedOwner] | ['ecs_nested_owner', 'ecs_deep_tags'] | 'ecs_deep_tags' | ['ecs_deep_id', 'tags_java_lang_string'] + 'a set of entities' | [EcsEntityOwner, EcsItem] | ['ecs_entity_owner', 'ecs_item', 'ecs_entities_ecs_item'] | 'ecs_entities_ecs_item' | ['ecs_entities_items_id', 'ecs_item_id'] + 'a set of entities in a nested type' | [EcsDeepEntityOwner, EcsItem] | ['ecs_deep_entity_owner', 'ecs_item', 'ecs_deep_entities_ecs_item'] | 'ecs_deep_entities_ecs_item' | ['ecs_deep_entities_items_id', 'ecs_item_id'] + } + + @Unroll + void "#label: the schema differs from the domain binder's only as the schema of a collection of the owner itself does"() { + when: + Map<String, Map> binder = schema(group, false) + Map<String, Map> generated = schema(group, true) + Map<String, Map> plainBinder = schema([plain], false) + Map<String, Map> plainGenerated = schema([plain], true) + + then: "the same tables, the same columns apart from the one the binder leaves unused, the same keys" + generated.keySet() == binder.keySet() + generated[table].columns.keySet() == binder[table].columns.keySet() - unused + generated[table].primaryKey == binder[table].primaryKey + generated[table].foreignKeys == binder[table].foreignKeys + generated[table].indexes == binder[table].indexes + generated[table].uniqueKeys == binder[table].uniqueKeys + + and: "the types differ exactly where they differ for a collection that is a property of the owner" + shape(binder[table].columns, generated[table].columns) == shape(plainBinder[plainTable].columns, plainGenerated[plainTable].columns) + + where: + label | group | table | unused | plain | plainTable + 'a list of strings' | [EcsListOwner] | 'ecs_lists_items' | [] | EcsPlainList | 'ecs_plain_list_items' + 'a map of strings' | [EcsMapOwner] | 'ecs_maps_by_name' | ['by_name_java_lang_string'] | EcsPlainMap | 'ecs_plain_map_by_name' + } + + private static List shape(Map<String, String> binder, Map<String, String> generated) { + return (binder.keySet() + generated.keySet()).collect { String name -> [binder[name], generated[name]] } + .findAll { List pair -> pair[0] != pair[1] }.sort { it.toString() } + } + + @Unroll + void "#label are stored, read back, changed and deleted with the owner, the same 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 + 'the words of an embedded set' | [EcsSetOwner] | 'setCycle' | [['a', 'b'], ['a', 'c'], 0] + 'the elements of an embedded list' | [EcsListOwner] | 'listCycle' | [['x', 'y', 'x'], ['y', 'z'], 0] + 'the entries of an embedded map' | [EcsMapOwner] | 'mapCycle' | [[one: 'a', two: 'b'], [two: 'b', three: 'c'], 0] + 'the colors of an embedded set' | [EcsEnumOwner] | 'enumCycle' | [['GREEN', 'RED'], ['GREEN'], 0] + 'the items of an embedded set' | [EcsEntityOwner, EcsItem] | 'entityCycle' | [['one', 'two'], ['three', 'two'], 0] + 'the items of a nested embedded set' | [EcsDeepEntityOwner, EcsItem] | 'deepEntityCycle' | [['one', 'two'], ['one', 'three', 'two'], 0] + 'the tags of a nested embedded set' | [EcsNestedOwner] | 'nestedCycle' | [['t1', 't2'], ['t2', 't3'], 0] + } + + private List setCycle() { + Long id = EcsSetOwner.withTransaction { new EcsSetOwner(inner: new EcsWords(words: ['a', 'b'] as Set)).save(failOnError: true, flush: true).id } + List first = EcsSetOwner.withNewSession { EcsSetOwner.get(id).inner.words.sort() } + EcsSetOwner.withTransaction { EcsSetOwner owner = EcsSetOwner.get(id); owner.inner.words = ['a', 'c'] as Set; owner.save(failOnError: true, flush: true) } + List second = EcsSetOwner.withNewSession { EcsSetOwner.get(id).inner.words.sort() } + EcsSetOwner.withTransaction { EcsSetOwner.get(id).delete(flush: true) } + return [first, second, countRows('ecs_words_words')] + } + + private List listCycle() { + Long id = EcsListOwner.withTransaction { new EcsListOwner(inner: new EcsLists(items: ['x', 'y', 'x'])).save(failOnError: true, flush: true).id } + List first = EcsListOwner.withNewSession { new ArrayList(EcsListOwner.get(id).inner.items) } + EcsListOwner.withTransaction { EcsListOwner owner = EcsListOwner.get(id); owner.inner.items = ['y', 'z']; owner.save(failOnError: true, flush: true) } + List second = EcsListOwner.withNewSession { new ArrayList(EcsListOwner.get(id).inner.items) } + EcsListOwner.withTransaction { EcsListOwner.get(id).delete(flush: true) } + return [first, second, countRows('ecs_lists_items')] + } + + private List mapCycle() { + Long id = EcsMapOwner.withTransaction { new EcsMapOwner(inner: new EcsMaps(byName: [one: 'a', two: 'b'])).save(failOnError: true, flush: true).id } + Map first = EcsMapOwner.withNewSession { new TreeMap(EcsMapOwner.get(id).inner.byName) } + EcsMapOwner.withTransaction { EcsMapOwner owner = EcsMapOwner.get(id); owner.inner.byName = [two: 'b', three: 'c']; owner.save(failOnError: true, flush: true) } + Map second = EcsMapOwner.withNewSession { new TreeMap(EcsMapOwner.get(id).inner.byName) } + EcsMapOwner.withTransaction { EcsMapOwner.get(id).delete(flush: true) } + return [first, second, countRows('ecs_maps_by_name')] + } + + private List enumCycle() { + Long id = EcsEnumOwner.withTransaction { new EcsEnumOwner(inner: new EcsEnums(colors: [EcsColor.RED, EcsColor.GREEN] as Set)).save(failOnError: true, flush: true).id } + List first = EcsEnumOwner.withNewSession { EcsEnumOwner.get(id).inner.colors*.name().sort() } + EcsEnumOwner.withTransaction { EcsEnumOwner owner = EcsEnumOwner.get(id); owner.inner.colors = [EcsColor.GREEN] as Set; owner.save(failOnError: true, flush: true) } + List second = EcsEnumOwner.withNewSession { EcsEnumOwner.get(id).inner.colors*.name().sort() } + EcsEnumOwner.withTransaction { EcsEnumOwner.get(id).delete(flush: true) } + return [first, second, countRows('ecs_enums_colors')] + } + + private List entityCycle() { + Long id = EcsEntityOwner.withTransaction { + EcsItem one = new EcsItem(name: 'one').save(failOnError: true) + EcsItem two = new EcsItem(name: 'two').save(failOnError: true) + new EcsEntityOwner(inner: new EcsEntities(items: [one, two] as Set)).save(failOnError: true, flush: true).id + } + List first = EcsEntityOwner.withNewSession { EcsEntityOwner.get(id).inner.items*.name.sort() } + EcsEntityOwner.withTransaction { + EcsItem three = new EcsItem(name: 'three').save(failOnError: true) + EcsEntityOwner owner = EcsEntityOwner.get(id) + owner.inner.items = [EcsItem.findByName('two'), three] as Set + owner.save(failOnError: true, flush: true) + } + List second = EcsEntityOwner.withNewSession { EcsEntityOwner.get(id).inner.items*.name.sort() } + EcsEntityOwner.withTransaction { EcsEntityOwner.get(id).delete(flush: true) } + return [first, second, countRows('ecs_entities_ecs_item')] + } + + private List deepEntityCycle() { + Long id = EcsDeepEntityOwner.withTransaction { + EcsItem one = new EcsItem(name: 'one').save(failOnError: true) + EcsItem two = new EcsItem(name: 'two').save(failOnError: true) + new EcsDeepEntityOwner(mid: new EcsMidEntities(label: 'm', deep: new EcsDeepEntities(items: [one, two] as Set))).save(failOnError: true, flush: true).id + } + List first = EcsDeepEntityOwner.withNewSession { EcsDeepEntityOwner.get(id).mid.deep.items*.name.sort() } + EcsDeepEntityOwner.withTransaction { + EcsDeepEntityOwner owner = EcsDeepEntityOwner.get(id) + owner.mid.deep.items.add(new EcsItem(name: 'three').save(failOnError: true)) + owner.save(failOnError: true, flush: true) + } + List second = EcsDeepEntityOwner.withNewSession { EcsDeepEntityOwner.get(id).mid.deep.items*.name.sort() } + EcsDeepEntityOwner.withTransaction { EcsDeepEntityOwner.get(id).delete(flush: true) } + return [first, second, countRows('ecs_deep_entities_ecs_item')] + } + + private List nestedCycle() { + Long id = EcsNestedOwner.withTransaction { new EcsNestedOwner(mid: new EcsMid(x: 'm', deep: new EcsDeep(tags: ['t1', 't2'] as Set))).save(failOnError: true, flush: true).id } + List first = EcsNestedOwner.withNewSession { EcsNestedOwner.get(id).mid.deep.tags.sort() } + EcsNestedOwner.withTransaction { EcsNestedOwner owner = EcsNestedOwner.get(id); owner.mid.deep.tags.remove('t1'); owner.mid.deep.tags.add('t3'); owner.save(failOnError: true, flush: true) } + List second = EcsNestedOwner.withNewSession { EcsNestedOwner.get(id).mid.deep.tags.sort() } + EcsNestedOwner.withTransaction { EcsNestedOwner.get(id).delete(flush: true) } + return [first, second, countRows('ecs_deep_tags')] + } + + 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 "the words of an embedded set are found by a query on the owner in both modes"() { + when: + List<List> results = [false, true].collect { boolean generated -> + boot([EcsSetOwner], generated) + EcsSetOwner.withTransaction { + new EcsSetOwner(inner: new EcsWords(words: ['red', 'blue'] as Set)).save(failOnError: true) + new EcsSetOwner(inner: new EcsWords(words: ['green'] as Set)).save(failOnError: true, flush: true) + } + EcsSetOwner.withNewSession { + [EcsSetOwner.count(), EcsSetOwner.list()*.inner.words.flatten().sort(), EcsSetOwner.executeQuery('select count(o) from EcsSetOwner o where o.id > 0')[0]] + } + } + + then: + results[1] == results[0] + results[1] == [2, ['blue', 'green', 'red'], 2] + } + + void "a type with a collection that two embedded properties share is rejected by the generated mode and says why"() { + when: "the domain binder cannot boot owners that embed the type under the same name" + boot([EmbeddedCollectionOwnerA, EmbeddedCollectionOwnerB], false) + + then: + thrown(Exception) + + when: + boot([EmbeddedCollectionOwnerA, EmbeddedCollectionOwnerB], true) + + then: + Exception e = thrown() + rootOf(e) instanceof UnsupportedOperationException + rootOf(e).message.contains('is reachable through 2 embedded properties') + rootOf(e).message.contains('EmbeddedCollectionOwnerA.inner') + rootOf(e).message.contains('EmbeddedCollectionOwnerB.inner') + } + + void "under different property names the domain binder boots but keeps one table with a key to the first owner, which the generated mode does not copy"() { + when: + Map<String, Map> binder = schema([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD], false) + + then: "one collection table, a foreign key to one of the owners" + binder.keySet().count { it.contains('words') } == 1 + binder.values().find { it.columns.containsKey('embedded_collection_holder_id') }.foreignKeys.size() == 1 + + when: "the second owner stores a collection" + EmbeddedCollectionOwnerD.withTransaction { + new EmbeddedCollectionOwnerD(second: new grails.unbootable.EmbeddedCollectionHolder(words: ['w'] as Set)).save(failOnError: true, flush: true) + } + + then: "its row violates the foreign key to the other owner" + thrown(Exception) + + when: + boot([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD], true) + + then: + Exception e = thrown() + rootOf(e) instanceof UnsupportedOperationException + rootOf(e).message.contains('EmbeddedCollectionOwnerC.first') + rootOf(e).message.contains('EmbeddedCollectionOwnerD.second') + } + + private static Throwable rootOf(Throwable e) { + Throwable root = e + while (root.cause != null && root.cause != root) { + root = root.cause + } + return root + } +} + +enum EcsColor { RED, GREEN } + +class EcsWords { + Set<String> words + static hasMany = [words: String] +} + +@Entity +class EcsSetOwner { + EcsWords inner + static embedded = ['inner'] +} + +class EcsMixedWords { + String label + Set<String> words + static hasMany = [words: String] +} + +@Entity +class EcsMixedOwner { + String name + EcsMixedWords inner + static embedded = ['inner'] +} + +class EcsEnums { + Set<EcsColor> colors + static hasMany = [colors: EcsColor] +} + +@Entity +class EcsEnumOwner { + EcsEnums inner + static embedded = ['inner'] +} + +class EcsNamed { + Set<String> words + static hasMany = [words: String] + static mapping = { + words joinTable: [name: 'ecs_named_words', key: 'owner_fk', column: 'word_col'] + } +} + +@Entity +class EcsNamedOwner { + EcsNamed inner + static embedded = ['inner'] +} + +class EcsDeep { + Set<String> tags + static hasMany = [tags: String] +} + +class EcsMid { + String x + EcsDeep deep + static embedded = ['deep'] +} + +@Entity +class EcsNestedOwner { + EcsMid mid + static embedded = ['mid'] +} + +class EcsLists { + List<String> items + static hasMany = [items: String] +} + +@Entity +class EcsListOwner { + EcsLists inner + static embedded = ['inner'] +} + +class EcsMaps { + Map<String, String> byName + static hasMany = [byName: String] +} + +@Entity +class EcsMapOwner { + EcsMaps inner + static embedded = ['inner'] +} + +@Entity +class EcsPlainList { + List<String> items + static hasMany = [items: String] +} + +@Entity +class EcsPlainMap { + Map<String, String> byName + static hasMany = [byName: String] +} + +@Entity +class EcsItem { + String name +} + +class EcsEntities { + Set<EcsItem> items + static hasMany = [items: EcsItem] +} + +@Entity +class EcsEntityOwner { + EcsEntities inner + static embedded = ['inner'] +} + +class EcsDeepEntities { + Set<EcsItem> items + static hasMany = [items: EcsItem] +} + +class EcsMidEntities { + String label + EcsDeepEntities deep + static embedded = ['deep'] +} + +@Entity +class EcsDeepEntityOwner { + EcsMidEntities mid + static embedded = ['mid'] +} diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/EmbeddedCollectionDomains.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/EmbeddedCollectionDomains.groovy index c32d620865..5ef6dc4cb7 100644 --- a/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/EmbeddedCollectionDomains.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/grails/unbootable/EmbeddedCollectionDomains.groovy @@ -46,3 +46,35 @@ class EmbeddedCollectionHolder { static hasMany = [words: String] } + +/** + * Two owners that embed the same type under different property names: the binder boots (the roles differ) but binds one collection + * table, whose key is a foreign key to the owner that was bound first. + */ +@Entity +class EmbeddedCollectionOwnerC { + + EmbeddedCollectionHolder first + + static embedded = ['first'] +} + +@Entity +class EmbeddedCollectionOwnerD { + + EmbeddedCollectionHolder second + + static embedded = ['second'] +} + +/** + * One owner that embeds the same type under two property names: the same single table again. + */ +@Entity +class EmbeddedCollectionOwnerTwice { + + EmbeddedCollectionHolder home + EmbeddedCollectionHolder work + + static embedded = ['home', 'work'] +} 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 2c5e1cc0d7..edc0b72504 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 @@ -83,7 +83,6 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { 'neither side of the many-to-many owns it', 'is registered for the Java type', 'names a class that is not a UserType', - 'is a collection inside an embedded type', 'declares a natural id but is a subclass', 'which is HibernateEmbeddedProperty', 'which is not a persistent property of the entity', 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 621b97914c..8e680c0873 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 @@ -209,7 +209,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } else { embeddedProperties++ embeddedLeaves += leaves.size() - mismatches.addAll(compareEmbedded(entity, embedded, leaves, generator, bound, explicitTypes, known)) + mismatches.addAll(compareEmbedded(entity, embedded, leaves, generator, bound, explicitTypes, known, collections, associations)) } continue } @@ -951,7 +951,8 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { */ private List<String> compareEmbedded( GrailsHibernatePersistentEntity entity, HibernateEmbeddedProperty property, List<EmbeddedLeaf> leaves, - GrailsDomainGenerator generator, Property bound, Map<String, Integer> explicitTypes, Map<String, Integer> known) { + GrailsDomainGenerator generator, Property bound, Map<String, Integer> explicitTypes, Map<String, Integer> known, + Map<String, Integer> collections, Map<String, Integer> associations) { List<String> found = [] String where = "${entity.name}.${property.name}" Map<String, Property> boundLeaves = terminalProperties(bound).collectEntries { String path, Property leaf -> @@ -984,6 +985,40 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } found.addAll(compareType(leafWhere, leaf.property, generator, boundLeaf, explicitTypes)) } + found.addAll(compareEmbeddedCollections(where, property, (Component) bound.value, generator, explicitTypes, known, collections, associations)) + return found + } + + /** + * A collection inside an embedded type has a table of its own and no leaf in the owner's table: the facets the generator decides + * for it are compared with the collection the binder bound inside the component, nested components included. + */ + private List<String> compareEmbeddedCollections( + String where, HibernateEmbeddedProperty property, Component component, GrailsDomainGenerator generator, + Map<String, Integer> explicitTypes, Map<String, Integer> known, Map<String, Integer> collections, + Map<String, Integer> associations) { + List<String> found = [] + GrailsHibernatePersistentEntity type = (GrailsHibernatePersistentEntity) property.associatedEntity + for (HibernatePersistentProperty peer : type.getHibernatePersistentProperties(property.owner.javaClass)) { + Property inner = component.properties.find { Property candidate -> candidate.name == peer.name } + if (inner == null) { + continue + } + String peerWhere = "${where}.${peer.name}".toString() + if (peer instanceof HibernateEmbeddedProperty && inner.value instanceof Component) { + found.addAll(compareEmbeddedCollections( + peerWhere, (HibernateEmbeddedProperty) peer, (Component) inner.value, generator, explicitTypes, known, collections, associations)) + } else if (peer instanceof HibernateToManyEntityProperty && inner.value instanceof HibernateCollection) { + ToManyFacets facets = generator.toManyFacets((HibernateToManyEntityProperty) peer) + associations["embedded ${facets.manyToMany() ? 'many-to-many' : 'one-to-many'}, ${facets.kind()}".toString()]++ + found.addAll(compareToMany(peerWhere, (HibernateToManyEntityProperty) peer, facets, inner, known)) + } else if (peer instanceof HibernateBasicProperty && inner.value instanceof HibernateCollection) { + CollectionFacets facets = generator.collectionFacets((HibernateBasicProperty) peer) + collections["embedded ${facets.kind()}${peer instanceof HibernateEnumProperty ? ' of enums' : ''}".toString()]++ + found.addAll(compareCollection( + peerWhere, (HibernateBasicProperty) peer, facets, generator, (HibernateCollection) inner.value, explicitTypes, known)) + } + } return found } @@ -994,7 +1029,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { for (Property inner : ((Component) property.value).properties) { if (inner.value instanceof Component) { terminalProperties(inner).each { String path, Property leaf -> result["${property.name}.${path}".toString()] = leaf } - } else { + } else if (!(inner.value instanceof HibernateCollection)) { result["${property.name}.${inner.name}".toString()] = inner } } 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 59ca4f2e65..5f107fb16e 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 @@ -26,6 +26,10 @@ import java.lang.reflect.Field import grails.gorm.annotation.Entity import grails.gorm.tests.HibernateGormDatastoreSpec +import grails.unbootable.EmbeddedCollectionHolder +import grails.unbootable.EmbeddedCollectionOwnerA +import grails.unbootable.EmbeddedCollectionOwnerB +import grails.unbootable.EmbeddedCollectionOwnerTwice import grails.unbootable.NoOwnerLeft import grails.unbootable.NoOwnerRight import jakarta.persistence.AssociationOverride @@ -162,7 +166,8 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { GenEmbedOwner, GenEmbedOther, GenEmbedBase, GenEmbedChild, GenEmbedFormulaOwner, GenCollSingle, GenCollKinds, GenCollLazy, 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) + GenMmStudent, GenMmCourse, GenMmPerson, GenParamsOnly, GenDecimal, GenUnversioned, GenUnversionedRoot, GenUnversionedChild, GenConverted, GenValueTyped, + GenCollEmbeddedHolder, GenCollEmbeddedSibling, GenCollEmbeddedItem, GenCollEmbeddedEntityHolder) } List<StandardServiceRegistry> registries = [] @@ -1325,12 +1330,70 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { e.message.contains('collectionFacets') } - void "a collection of basic values inside an embedded type is rejected by name"() { + void "a collection of basic values inside an embedded type is an element collection of the embeddable, named after the embedded type"() { given: GrailsHibernatePersistentEntity holder = unbound(GenCollEmbeddedHolder) + Class<?> owner = generate(GenCollEmbeddedHolder) + Class<?> embeddable = owner.getDeclaredField('inner').type + Field words = embeddable.getDeclaredField('words') expect: - newGenerator().unsupportedReason(holder, holder.getHibernatePropertyByName('inner')).contains('collection inside an embedded type') + newGenerator().supports(holder.getHibernatePropertyByName('inner')) + words.isAnnotationPresent(ElementCollection) + words.getAnnotation(CollectionTable).name() == 'gen_coll_embedded_words' + words.getAnnotation(CollectionTable).joinColumns()*.name() == ['gen_coll_embedded_id'] + words.getAnnotation(Column).name() == 'words_java_lang_string' + embeddable.name == 'org.grails.orm.hibernate.generated.org_grails_orm_hibernate_cfg_domainbinding_jpa_GenCollEmbedded_Embeddable' + + and: "the collection has no column of the owner's table, so the owner overrides none for it" + newGenerator().embeddedLeaves(holder.getHibernatePropertyByName('inner') as HibernateEmbeddedProperty).isEmpty() + !owner.getDeclaredField('inner').isAnnotationPresent(AttributeOverrides) + } + + void "a collection of entities inside an embedded type is a to-many of the embeddable, which takes the name of the embedded type"() { + given: + Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenCollEmbeddedEntityHolder, GenCollEmbeddedItem) + Class<?> owner = classes[entity(GenCollEmbeddedEntityHolder)] + Class<?> embeddable = owner.getDeclaredField('inner').type + Field items = embeddable.getDeclaredField('items') + + expect: "Hibernate retries without end the element check of a collection whose declaring class it resolves to the real embedded class" + embeddable.name == GenCollEmbeddedEntities.name + embeddable.isAnnotationPresent(Embeddable) + items.genericType.typeName == 'java.util.Set<' + GenCollEmbeddedItem.name + '>' + items.getAnnotation(ManyToMany).fetch() == FetchType.LAZY + items.getAnnotation(JoinTable).name() == 'gen_coll_embedded_entities_gen_coll_embedded_item' + items.getAnnotation(JoinTable).joinColumns()*.name() == ['gen_coll_embedded_entities_items_id'] + } + + void "an embedded type that has a collection is rejected when a second embedded property shares it"() { + when: + newGenerator().generateAll([unbound(EmbeddedCollectionOwnerA), unbound(EmbeddedCollectionOwnerB)], getClass().classLoader) + + then: + UnsupportedOperationException e = thrown() + e.message.contains('The collection [words] of the embedded type [' + EmbeddedCollectionHolder.name + ']') + e.message.contains('is reachable through 2 embedded properties') + e.message.contains(EmbeddedCollectionOwnerA.name + '.inner') + e.message.contains(EmbeddedCollectionOwnerB.name + '.inner') + } + + void "an owner that embeds the same type with a collection twice is rejected"() { + when: + newGenerator().generateAll([unbound(EmbeddedCollectionOwnerTwice)], getClass().classLoader) + + then: + UnsupportedOperationException e = thrown() + e.message.contains('is reachable through 2 embedded properties') + e.message.contains(EmbeddedCollectionOwnerTwice.name + '.home') + e.message.contains(EmbeddedCollectionOwnerTwice.name + '.work') + } + + void "owners that embed different types with collections are generated together"() { + expect: + generateGroup(GenCollEmbeddedHolder).size() == 1 + newGenerator().generateAll( + [unbound(GenCollEmbeddedHolder), unbound(GenCollEmbeddedSibling)], getClass().classLoader).size() == 2 } void "a to-one association is a field typed with the class generated for its target, in the same class loader"() { @@ -2058,6 +2121,9 @@ class GenEmbedBad { Set<String> ref static hasMany = [ref: String] + static mapping = { + ref type: 'text' + } } @Entity @@ -2179,6 +2245,42 @@ class GenCollEmbedded { static hasMany = [words: String] } +@Entity +class GenCollEmbeddedSibling { + + GenCollOther inner + + static embedded = ['inner'] +} + +class GenCollOther { + + Set<String> tags + + static hasMany = [tags: String] +} + +@Entity +class GenCollEmbeddedItem { + + String name +} + +@Entity +class GenCollEmbeddedEntityHolder { + + GenCollEmbeddedEntities inner + + static embedded = ['inner'] +} + +class GenCollEmbeddedEntities { + + Set<GenCollEmbeddedItem> items + + static hasMany = [items: GenCollEmbeddedItem] +} + @Entity class GenBasic { 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 d674f4465c..97c796475c 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -60,6 +60,7 @@ For the domain classes in GORM's own test suites, both bindings produce the same * Properties mapped with a `UserType` class, and with the registered converter types `yes_no`, `true_false` and `numeric_boolean`, are stored as before. * 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. * 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]] @@ -75,9 +76,9 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | Message of the root cause | What to do -| A collection inside an embedded class: a `hasMany` of basic values in a class listed in `static embedded`. -| `... is a collection inside an embedded type ...` -| Move the collection to the owning domain class, or make the embedded class a domain class and map an association. Classic binding boots this only in some cases, and fails when two classes embed the type. +| A collection inside an embedded class that two embedded properties share: a `hasMany` in a class listed in `static embedded`, where more than one property of the application (of one domain class or of several) embeds that class. +| `The collection [...] of the embedded type [...] is reachable through N embedded properties (...) ...` +| Embed the class from one property only, or make it a domain class and map an association. Classic binding names the table and the key column of the collection after the embedded class, so all the owners share one table whose foreign key points at only one of them, and it fails to boot when the owners name the property alike. | A natural id declared on a subclass. | `Entity [...] declares a natural id but is a subclass ...` @@ -167,7 +168,7 @@ Some bugs of classic binding are not copied by native binding. Native binding do [[nativeDomainBinding-schema]] === Differences in the Schema -The schema of 663 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 12 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 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. [cols="2,3,3", options="header"] |===
